相关疑难解决方法(0)

为什么Python代码在函数中运行得更快?

def main():
    for i in xrange(10**8):
        pass
main()
Run Code Online (Sandbox Code Playgroud)

Python中的这段代码运行(注意:时序是在Linux中的BASH中使用时间函数完成的.)

real    0m1.841s
user    0m1.828s
sys     0m0.012s
Run Code Online (Sandbox Code Playgroud)

但是,如果for循环没有放在函数中,

for i in xrange(10**8):
    pass
Run Code Online (Sandbox Code Playgroud)

然后它会运行更长的时间:

real    0m4.543s
user    0m4.524s
sys     0m0.012s
Run Code Online (Sandbox Code Playgroud)

为什么是这样?

python performance benchmarking profiling cpython

809
推荐指数
3
解决办法
6万
查看次数

为什么将模块级代码放入函数中然后在Python中调用函数更快?

在Alex Martelli对使用Python脚本面向对象的回应中,他提到将模块级代码放入函数中然后在Python中调用函数更快.有人可以解释为什么以及它是否适用于所有Python实现?

python optimization module function

6
推荐指数
1
解决办法
322
查看次数