我使用 timeit 做了一个小函数,这样我就可以偷懒,少打字,但结果却没有按计划进行。
(相关)代码:
def timing(function, retries=10000, formatSeconds=3, repeat=10):
"""Test how long a function takes to run. Defaults are set to run
10 times of 10000 tries each. Will display time as 1 of 4 types.
0 = Seconds, 1 = milliseconds, 2= microseconds and 3 = nanoseconds.
Pass in paramaters as: (function, retries=10000,formatSeconds=3, repeat=10)"""
t = timeit.Timer(lambda: function)
result = t.repeat(repeat=repeat,number=retries)
rlist = [i/retries for i in result]
它运行良好,但它不断返回:
timeprofile.timing(find_boundaries(numpy.asarray(Image.open(
r'D:\Python\image\image4.jpg')),79))
10 runs of 10000 cycles each:
Best time: 137.94764 Worst:158.16651 Avg: 143.25466 nanosecs/pass
现在,如果我通过解释器这样做:
import timeit
from timeit import Timer
t = timeit.Timer(lambda: (find_boundaries(numpy.asarray(Image.open(r'D:\Python\image\image4.jpg')),79)))
result = t.repeat(repeat=5,number=100)
result = [i/100 for i in result]
我最终得到[0.007723014775432375, 0.007615270149786965, 0.0075242365377505395,
0.007420834966038683, 0.0074086862470653615]
,或大约 8 毫秒。
如果我在脚本上运行探查器,它也会给出大约相同的结果,大约 8 毫秒。
我不太确定问题是什么,尽管我认为它与它调用函数的方式有关。当我检查调试器中的数据时,它将该函数显示为长度为 53 的字典,每个键包含 1 到 15 个元组,每个元组中有一对 2-3 位数字。
所以,如果有人知道为什么会这样做,并愿意向我解释它以及如何解决它,那就太好了!
最佳答案
是的,有区别。当你运行时:
timeprofile.timing(find_boundaries(numpy.asarray(Image.open(
r'D:\Python\image\image4.jpg')),79))
您没有传递函数引用。您正在调用该函数,而是传入该调用的结果。您正在计时staticresult
,而不是somefunction(with,arguments)
。
移出 lambda:
timeprofile.timing(lambda: (find_boundaries(numpy.asarray(Image.open(
r'D:\Python\image\image4.jpg')),79)))
这意味着您需要将其从 timing
函数中删除,并将该函数直接传递给 Timer()
类:
t = timeit.Timer(function)
关于python - timeit.timer 在我自己的函数中使用它与从命令行调用它时给出截然不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14715853/