我如何使用timeit来比较我自己的函数(如“insertion_sort”和“tim_sort”)的性能?


当前回答

如果你想在交互式Python会话中使用timeit,有两个方便的选项:

Use the IPython shell. It features the convenient %timeit special function: 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 In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__ in the setup statement: >>> 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]

其他回答

这很有效:

  python -m timeit -c "$(cat file_name.py)"

对我来说,这是最快的方法:

import timeit
def foo():
    print("here is my code to time...")


timeit.timeit(stmt=foo, number=1234567)

如果你想在交互式Python会话中使用timeit,有两个方便的选项:

Use the IPython shell. It features the convenient %timeit special function: 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 In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__ in the setup statement: >>> 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]

简单地传递你的整个代码作为timeit参数:

import timeit

print(timeit.timeit(

"""   
limit = 10000
prime_list = [i for i in range(2, limit+1)]

for prime in prime_list:
    for elem in range(prime*2, max(prime_list)+1, prime):
        if elem in prime_list:
            prime_list.remove(elem)
"""   
, number=10))

让我们在以下每个语句中设置相同的字典并测试执行时间。

setup参数基本上是设置字典

编号是运行代码1000000次。不是设置,而是stmt

当你运行这个时,你会发现index比get快得多。您可以多次运行它来查看。

这段代码基本上是试图从字典中获取c的值。

import timeit

print('Getting value of C by index:', timeit.timeit(stmt="mydict['c']", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))
print('Getting value of C by get:', timeit.timeit(stmt="mydict.get('c')", setup="mydict={'a':5, 'b':6, 'c':7}", number=1000000))

这是我的结果,你的结果会有所不同。

按索引:0.20900007452246427

get: 0.54841166886888