为什么Python代码在函数中运行得更快? [英] Why does Python code run faster in a function?

查看:112
本文介绍了为什么Python代码在函数中运行得更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def main():
    for i in xrange(10**8):
        pass
main()

这部分Python代码在其中运行(注意:计时是通过Linux中的BASH中的time函数完成的.)

This piece of code in Python runs in (Note: The timing is done with the time function in BASH in Linux.)

real    0m1.841s
user    0m1.828s
sys     0m0.012s

但是,如果在函数中未放置for循环,则

However, if the for loop isn't placed within a function,

for i in xrange(10**8):
    pass

然后运行更长的时间:

real    0m4.543s
user    0m4.524s
sys     0m0.012s

这是为什么?

推荐答案

您可能会问为什么存储局部变量要比全局变量快.这是CPython的实现细节.

You might ask why it is faster to store local variables than globals. This is a CPython implementation detail.

请记住,CPython已编译为解释程序运行的字节码.编译函数时,局部变量存储在固定大小的数组中( not a dict),并将变量名称分配给索引.这是可能的,因为您不能动态地将局部变量添加到函数中.然后,从字面上查找指向列表的指针并在PyObject上增加refcount是很简单的.

Remember that CPython is compiled to bytecode, which the interpreter runs. When a function is compiled, the local variables are stored in a fixed-size array (not a dict) and variable names are assigned to indexes. This is possible because you can't dynamically add local variables to a function. Then retrieving a local variable is literally a pointer lookup into the list and a refcount increase on the PyObject which is trivial.

将此与全局查找(LOAD_GLOBAL)进行对比,这是一个真正的dict搜索,涉及哈希等.顺便说一句,这就是为什么要使其为全局变量时需要指定global i的原因:如果您在作用域内分配了一个变量,则编译器将发出STORE_FAST的访问权限,除非您告知不要这样做.

Contrast this to a global lookup (LOAD_GLOBAL), which is a true dict search involving a hash and so on. Incidentally, this is why you need to specify global i if you want it to be global: if you ever assign to a variable inside a scope, the compiler will issue STORE_FASTs for its access unless you tell it not to.

顺便说一句,全局查找仍然非常优化.属性查询foo.bar是真正的 慢速查询!

By the way, global lookups are still pretty optimised. Attribute lookups foo.bar are the really slow ones!

这里关于局部变量效率的插图很小.

Here is small illustration on local variable efficiency.

这篇关于为什么Python代码在函数中运行得更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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