我该如何使用timeit比较我自己的功能的性能,例如“insertion_sort
" and "tim_sort
"?
如果你想使用timeit
在交互式 Python 会话中,有两个方便的选项:
-
Use the IPython壳。其特点是方便%timeit
特殊功能:
In [1]: def f(x):
...: return x*x
...:
In [2]: %timeit for x in range(100): f(x)
100000 loops, best of 3: 20.3 us per loop
-
在标准 Python 解释器中,您可以通过从以下位置导入函数和先前在交互式会话期间定义的其他名称来访问它们:__main__
在设置语句中:
>>> def f(x):
... return x * x
...
>>> import timeit
>>> timeit.repeat("for x in range(100): f(x)", "from __main__ import f",
number=100000)
[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)