5.8 如何快速计算函数运行时间 ============================ .. image:: http://image.iswbm.com/20200804124133.png 计算一个函数的运行时间,你可能会这样子做 .. code:: python import time start = time.time() # run the function end = time.time() print(end-start) 你看看你为了计算函数运行时间,写了几行代码了。 ​ 有没有一种方法可以更方便地计算这个运行时间呢? ​ 有。 ​ 有一个内置模块叫 timeit ​ 使用它,只用一行代码即可 .. code:: python import time import timeit def run_sleep(second): print(second) time.sleep(second) # 只用这一行 print(timeit.timeit(lambda :run_sleep(2), number=5)) 运行结果如下 .. code:: python 2 2 2 2 2 10.020059824