不明白 Timeit 是如何工作的。需要一个解释

Don't understand how Timeit works. Need an explanation

我不明白我是如何让 timeit 工作的。我举了一个例子,我想计算处理时间的差异。如果有人有时间为我分解它,我将永远感激不已。

低音

def main():
    prod_nums = ['V475', 'F987', 'Q143', 'R688']

def search_fast(prod_nums):
    for item in prod_nums:
        if item == 'R688':
            return True
    return False

def search_slow(prod_nums):
    return_value = False
    for item in prod_nums:
        if item == 'R688': 
            return_value = True
    return return_value

如果你想将参数传递给你的函数,你可能想使用 timeit.Timer,但是像这样使你的列表成为全局的:

prod_nums = ['V475', 'F987', 'Q143', 'R688']

然后 运行 这个:

from timeit import Timer
t = Timer(lambda: search_fast(prod_nums))
print t.timeit() # In my case will print 0.336354970932
t = Timer(lambda: search_slow(prod_nums))
print t.timeit() # 0.374251127243

timeit 当您想在开发环境中检查一小段代码时很有用。

如果您的函数看起来像这样:

def search_slow():
    prod_nums = ['V475', 'F987', 'Q143', 'R688']
    return_value = False
    for item in prod_nums:
        if item == 'R688':
            return_value = True
    return return_value

您可以使用timeit.timeit

import timeit
timeit.timeit(search_slow)
>>> 0.3833189010620117

这不会return任何结果,只是花费的时间。这是另一个可以使用装饰器的场景。 基本上,您可以使用 timeit 来告诉您函数执行需要多少时间,就像终端中的 time sample_file.py 一样。

基于 python 文档 (https://docs.python.org/2/library/timeit.html): This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.