[英]Don't understand how Timeit works. Need an explanation
I don't understand how I get timeit
to work. 我不明白我怎么弄
timeit
工作。 I've made an example, where I want to calculate the difference in processing times. 我举了一个例子,我想计算处理时间的差异。 I would be eternally grateful if someone have the time to break it down for me.
如果有人有时间为我分解,我将永远感激不已。
Basse 巴斯
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
If you want to pass arguments to your function you might want to use timeit.Timer
, but make your list global like this: 如果要将参数传递给函数,则可能要使用
timeit.Timer
,但应使列表全局,如下所示:
prod_nums = ['V475', 'F987', 'Q143', 'R688']
And then run this: 然后运行:
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
is useful when you want to inspect small piece of code in your dev environment. 当您想在开发环境中检查一小段代码时,
timeit
很有用。
If your function looks like that: 如果您的函数如下所示:
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
You can use timeit.timeit
您可以使用
timeit.timeit
import timeit
timeit.timeit(search_slow)
>>> 0.3833189010620117
This will not return any result thou, only the time it took. 您只会返回花费的时间,而不会返回任何结果。 This is another scenario in which you can use decorator.
这是可以使用装饰器的另一种方案。 Basically you can use
timeit
to tell you how much time does it take for a function to execute, much like time sample_file.py
in your terminal. 基本上,您可以使用
timeit
告诉您执行一个函数需要多少time sample_file.py
,就像终端中的time sample_file.py
一样。
Based on python docs ( 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.
基于python docs( 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.
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.