timeit.timer在我自己的函数中使用它时会给出远远不同的结果,而不是从命令行调用它

时间:2013-02-05 19:56:23

标签: python timeit

我使用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毫秒的结果。

我不确定问题是什么,虽然我认为它与它如何调用函数有关。当我检查调试器中的数据时,它将函数显示为len为53的字典,每个键包含1到15个元组,每个元组中有一对2-3位数字。

所以,如果有人知道它为什么这样做并想向我解释,以及如何解决它,那就太好了!

1 个答案:

答案 0 :(得分: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)