如何使用timeit模块 [英] How to use timeit module
问题描述
我了解timeit
的概念,但不确定如何在代码中实现.
I understand the concept of what timeit
does but I am not sure how to implement it in my code.
如何将insertion_sort
和tim_sort
这两个函数与timeit
进行比较?
How can I compare two functions, say insertion_sort
and tim_sort
, with timeit
?
推荐答案
Timsort 确实令人眼前一亮,因为当数据已经部分排序时,它的性能最佳.
The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).
以下是如何设置分类测试的示例:
Here is an example of how to set up a test for sorting:
>>> import timeit
>>> setup = '''
import random
random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = list.sort
'''
>>> print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000))
0.334147930145
请注意,这一系列语句在每次通过时都会对未排序的数据进行全新复制.
Note that the series of statements makes a fresh copy of the unsorted data on every pass.
另外,请注意运行测量套件七次并仅保留最佳时间的计时技术-这确实可以帮助减少由于系统上正在运行其他进程而导致的测量失真.
Also, note the timing technique of running the measurement suite seven times and keeping only the best time -- this can really help reduce measurement distortions due to other processes running on your system.
这些是我正确使用timeit的提示.希望这会有所帮助:-)
Those are my tips for using timeit correctly. Hope this helps :-)
这篇关于如何使用timeit模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!