timeit 基本信息
timeit是python内置的模块; 主要用来 测量 几行简短代码或 一个函数的 执行时间;
使用方式
在脚本中运行
1.使用 timeit.repeat 方法,主要功能为 重复测量多个回合,每个回合默认执行一百万次,结果 是一个长度为 回合次数的list; 参数如下:
- stmt: 被测量的主体代码部分,可以是字符串类型的代码,或 可调用的函数名;
- setup: 被测量的主体代码依赖的 导入等;可以是字符串类型的代码,或 可调用的函数名;
- timer: 计数器; 默认为: time.perf_counter:用于基准测试的性能计数器;
- repeat: 重复测量回合数; 默认3回合
- number: 每回合测量次数; 默认为 1000000(一百万) 次;
- globals: 将 globals() 值传递给此参数,这将导致代码在当前的全局命名空间中执行。这样 就不用在 setup参数中 单独指定 import 代码了;
2.使用 timeit.timeit 方法,主要功能为 值测量一个回合,默认执行1百万次;结果是一个 数字; 参数 只比上面的 timeit.repeat的参数少一个 repeat; 其他相同;
代码示例(被测函数不带参数):
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import timeit
from math import sin
def tight_loop_slow():
"""
每次循环 要去 全局变量中找 sin方法,较慢
"""
result = 0
for i in range(iterations):
# this call to sin requires a global lookup
result += sin(i)
def tight_loop_fast():
"""
每次循环 直接在 本地变量中寻找 sin方法,较快
"""
result = 0
local_sin = sin
for i in range(iterations):
# this call to local_sin requires a local lookup
result += local_sin(i)
if __name__ == '__main__':
iterations = 10000000
print('使用 repeat方法')
# 重复测试, 使用globals参数,不再需要setup参数
x = timeit.repeat(stmt=tight_loop_slow, number=2, globals=globals())
print(x)
# 重复测试, 使用setup参数 字符串指定导入,不提倡,费劲
x = timeit.repeat(stmt=tight_loop_fast, setup="from __main__ import tight_loop_fast", number=2)
print(x)
print('使用timeit方法')
# 重复测试, 使用globals参数,不再需要setup参数
x = timeit.timeit(stmt=tight_loop_slow, number=2, globals=globals())
print(x)
# 重复测试, 使用setup参数 字符串指定导入,不提倡,费劲
x = timeit.timeit(stmt=tight_loop_fast, setup="from __main__ import tight_loop_fast", number=2)
print(x)
运行结果如下:
示例代码(被测函数带参数)
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import timeit
from math import sin
def tight_loop_slow(iterations):
"""
每次循环 要去 全局变量中找 sin方法,较慢
"""
result = 0
for i in range(iterations):
# this call to sin requires a global lookup
result += sin(i)
if __name__ == '__main__':
print('使用 repeat方法')
# 被测函数带参数时, stmt参数值 只能用字符串表示
x = timeit.repeat(stmt="tight_loop_slow(1000000)", number=2, globals=globals())
print(x)
在命令行中运行
示例如下:
python -m timeit -s 'id(1)==id(1)'
运行结果:
由于感觉用处较少,此处只简单介绍一下,具体用法及参数解释请 点击链接
注意:
如上 所有知识均 基于python3.6版本;
相关链接: