相关疑难解决方法(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万
查看次数

标签 统计

benchmarking ×1

cpython ×1

performance ×1

profiling ×1

python ×1