为什么python中的函数/方法调用很昂贵? [英] Why is a function/method call in python expensive?

查看:67
本文介绍了为什么python中的函数/方法调用很昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇博文中,Guido van Rossum 说函数调用可能很昂贵,但我不明白为什么,也不明白会贵多少.

一个简单的函数调用会给您的代码增加多少延迟,为什么?

解决方案

一个函数调用要求挂起当前执行帧,并创建一个新的帧并压入堆栈.与许多其他操作相比,这是相对昂贵的.

您可以使用 timeit 模块测量所需的确切时间:

<预><代码>>>>导入时间>>>def f(): 通过...>>>timeit.timeit(f)0.15175890922546387

对于一百万次调用一个空函数来说,这是 1/6 秒;您将所需的时间与您想放入函数的时间进行比较;如果性能有问题,则需要考虑 0.15 秒.

In this post, Guido van Rossum says that a function call may be expensive, but I do not understand why nor how much expensive can be.

How much delay adds to your code a simple function call and why?

解决方案

A function call requires that the current execution frame is suspended, and a new frame is created and pushed on the stack. This is relatively expensive, compared to many other operations.

You can measure the exact time required with the timeit module:

>>> import timeit
>>> def f(): pass
... 
>>> timeit.timeit(f)
0.15175890922546387

That's 1/6th of a second for a million calls to an empty function; you'd compare the time required with whatever you are thinking of putting in a function; the 0.15 second would need to taken into account, if performance is an issue.

这篇关于为什么python中的函数/方法调用很昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆