一些让我对 python 发疯的东西......我曾经认为它是 just Windows ,但我错了。我可以拥有完全相同的代码并多次运行它,它的执行时间却大不相同。以下面的测试代码为例:

import math
def fib(count):
    x = 0
    while x < count:
        a = int(((((1 + math.sqrt(5)) / 2) ** x) - (((1 - math.sqrt(5)) / 2) ** (x))) / math.sqrt(5))
        x+=1

if __name__ == '__main__':
    import timeit

    t = timeit.Timer("fib(1250)", setup="from __main__ import fib",)
    #print t.timeit(10)
    count = 10000
    results = t.repeat(count, 1)
    min = 0xFFFF
    max = 0
    sum = 0
    for i in results:
        i = i*1000.0
        if i < min: min = i
        if i > max: max = i
        sum+=i

    print "Min {:.3f} | Max {:.3f} | Max/Min {:.3f} | Avg {:.3f}".format(min, max, max/min, sum/count)

基本上,它生成 fibonacii 的前 1250 个元素 10,000 次,并使用 timeit 来获取每次运行所需的时间。然后我合并这些时间并找到最小值、最大值、平均值和最小值和最大值之间的方差(如果你愿意的话,可以扩展)。

结果如下:
Windows: Min 3.071 | Max 8.903 | Max/Min 2.899 | Avg 3.228
Mac OS:  Min 1.531 | Max 3.167 | Max/Min 2.068 | Avg 1.621
Ubuntu:  Min 1.242 | Max 10.090 | Max/Min 8.123 | Avg 1.349

所以,Linux 是最快的,但也有最大的差异。很多。但是所有这些都可以有一个相当大的波动:Mac 只有 200%,但 Windows 是 290%,Linux 是 810%!

执行起来真的需要那么多不同的时间吗?时间不够准确?还有什么我想念的吗?我在生成动画方面做了很多工作,我需要尽可能一致的时间。

最佳答案

您测量的时间非常短,然后即使某处发生的一点点事情也会产生很大的影响。

我在我的机器(OS X、Core i7、Python 2.7)上运行了你的测试脚本,并制作了 results 的这个图:

您可以看到大部分时间的计时结果都非常一致,但是有一些孤立的算法事件需要花费更多的时间(因为还有其他事情发生)。

我对你的计时程序做了一个微小的调整:

results=t.repeat(10, 1000)

所以,现在我们计时运行 1000 次函数调用。总时间是一样的,自然是(10000次调用):

现在您可以看到性能更加可预测。可能你的部分时间不稳定是由于时间方法,而不是由于执行任何事情的时间不同。在现实世界的操作系统环境中,毫秒级计时是很困难的。即使您的计算机“无所事事”,它仍在切换任务、执行后台作业等。

我明白原点不是计算斐波那契数。但如果是这样,那么选择正确的工具会有所作为:
import numpy as np

def fib(count):
    x = np.arange(count)
    a = (((1 + np.sqrt(5))/2) ** x - ((1 - np.sqrt(5)) / 2) ** x) / np.sqrt(5)
    a = a.astype('int')

这给出:
Min 0.120 | Max 0.471 | Max/Min 3.928 | Avg 0.125

十倍速度提升。

关于这个答案中的图像,它们是用 matplotlib 绘制的。第一个是这样完成的:
import matplotlib.pyplot as plt

# create a figure
fig = plt.figure()
# create axes into the figure
ax = fig.add_subplot(111)
# plot the vector results with dots of size 2 (points) and semi-transparent blue color
ax.plot(results, '.', c=(0, 0, 1, .5), markersize=2)

请参阅 matplotlib 的文档。使用 IPythonpylab 最容易上手。

10-07 19:32
查看更多