[Python3] 029 常用模块 timeit

Posted YorkFish

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Python3] 029 常用模块 timeit相关的知识,希望对你有一定的参考价值。

timeit

直接举例

  • 必要的导入
import timeit

1. 测量生成列表的时间

  • 像是 C 或者 Js 中把函数作为参数传入
>>> func = '''
... arr = []
... for i in range(1000):
...   arr.append(i)
... '''
>>> t1 = timeit.timeit(stmt=func, number=10000)
>>> t2 = timeit.timeit(stmt="[i for i in range(1000)]", number=10000)
>>> t1
1.0912232999999105
>>> t2
0.5270981999999549
  • 可以看出,列表生成式比 "append" 快

2. 测量函数运行时间(一)

  • 公共部分
>>> def func(num=3):
...   for i in range(num):
...     print(f"Repeat for {i}.")
...
>>> 
  • 版本一
>>> t = timeit.timeit(stmt=func, number=5)
Repeat for 0.
Repeat for 1.
Repeat for 2.
Repeat for 0.
Repeat for 1.
Repeat for 2.
Repeat for 0.
Repeat for 1.
Repeat for 2.
Repeat for 0.
Repeat for 1.
Repeat for 2.
Repeat for 0.
Repeat for 1.
Repeat for 2.
>>> t
0.0009049000000231899
  • 版本二
>>> t = timeit.timeit(stmt=func, setup="func"+"num=5", number=5)
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
>>> t
0.008177499999874271
  • t = timeit.timeit(func, setup="funcnum=5", number=5) 也行,但不直观

3. 测量函数运行时间(二)

>>> s = '''
... def func(num):
...   for i in range(num):
...     print(f"Repeat for {i}")
... '''
>>> t = timeit.timeit(stmt="func(num)", setup=s+"num=3", number=5)
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
Repeat for 0
Repeat for 1
Repeat for 2
>>> t
0.0020025999997415056

以上是关于[Python3] 029 常用模块 timeit的主要内容,如果未能解决你的问题,请参考以下文章

Timeit模块

timeit模块

Python timeit模块

Python timeit模块的使用

如何使用timeit模块

python之timeit模块