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)
为什么是这样?
在Alex Martelli对使用Python脚本面向对象的回应中,他提到将模块级代码放入函数中然后在Python中调用函数更快.有人可以解释为什么以及它是否适用于所有Python实现?
python ×2
benchmarking ×1
cpython ×1
function ×1
module ×1
optimization ×1
performance ×1
profiling ×1