为什么在相同的输入下运行相同的功能两次浪费不同的时间在python?

时间:2017-08-31 11:48:04

标签: python performance math floating-point

下面的python代码尝试两次运行相同的函数并输出运行时:

def test_f(f1,ip):
    st = time.time()
    f1(*ip)
    print(time.time()-st)

test_f(math.sin,[100])
test_f(math.sin,[100])

三项测试的结果如下:

7.15255737305e-06
1.19209289551e-06

7.86781311035e-06
9.53674316406e-07

6.91413879395e-06
9.53674316406e-07

我不知道为什么输出如此不同?为什么第二次执行比第一次更快?我也尝试跑了五次,结果如下:

8.10623168945e-06
1.19209289551e-06
0.0
0.0
0.0

1 个答案:

答案 0 :(得分:1)

在CPython中,编译模块时,会创建一个代码对象(包含字节代码),但实际的函数调用需要一个框架对象(涉及一些运行时分配和初始化)。作为一种优化,这些框架对象有时会保持活力,因为"僵尸"供以后重复使用。以下是frameobject.c来源广泛评论的一部分:

  

/ *堆栈帧以相当大的速率分配和释放。       为了提高函数调用的速度,我们:

1. Hold a single "zombie" frame on each code object. This retains 
the allocated and initialised frame object from an invocation of 
the code object. The zombie is reanimated the next time we need a 
frame object for that code object. Doing this saves the malloc/ 
realloc required when using a free_list frame that isn't the 
correct size. It also saves some field initialisation.

如果您观察的内容不是time.time在该分辨率下不可靠的简单工件,那么创建僵尸(较慢)和恢复僵尸(更快)之间的时间差异。

相关问题