Python代码时间测试
- %%测试整个运行单元,而%测试某一行代码
- %time输出的含义:wall time 实际时间,从运行到结束,最直观的,人感受到的,包括其中一些等待输入输出的时间
- %time中CPU time为CPU处理代码的时间,其中user是在用户模式下(内核外面)使用CPU的时间,而sys是在内核中使用CPU的时间,两者和为CPU时间
- %timeit参数:r = repeats 即重复代码行或者代码块儿多少次;n = number 即每一次repeat循环执行多少次;所以共运行n*r次
- 那么为什么有r和n的区别呢?目的不同。r为了算平均值和标准差,而n是为了取最小值即最快的执行时间。
- 换言之,r = 3, n = 100 时,每100次运行取一次最小值,共取出三个最小值,再对这三个最小值计算平均值和标准差
以下面两个函数为例子:
def test_fun1():
a = list(range(10000))
def test_fun2():
a= [i for i in range(10000)]
%time
- 测试整个代码块儿,%%timeit 和 %%time 必须放在代码最前面,后面不能直接接语句
- %%time 和 %time 只运行一次代码
%%time
test_fun1()
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 563 µs
%%time
test_fun2()
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 819 µs
- 测试一行%time,可以放在代码中间
print('hello world!')
%time test_fun1()
print('end!')
hello world!
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 428 µs
end!
%timeit
- timeit 默认参数r = 7, n = 1000, 即实际运行代码7000次
%%timeit
test_fun1()
198 µs ± 18.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%%timeit
test_fun2()
305 µs ± 31.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
- 测试一行%timeit,可以放在代码中间
print('hello world!')
%timeit test_fun1()
hello world!
178 µs ± 21.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
- 指定r和n
%%timeit -r 2 -n 5
test_fun1()
435 µs ± 34.1 µs per loop (mean ± std. dev. of 2 runs, 5 loops each)
%%timeit -r 10 -n 10
test_fun1()
363 µs ± 56.4 µs per loop (mean ± std. dev. of 10 runs, 10 loops each)
- 当r逐渐变大
%%timeit -r 1 -n 10
test_fun1()
458 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 10 loops each)
%%timeit -r 2 -n 10
test_fun1()
439 µs ± 642 ns per loop (mean ± std. dev. of 2 runs, 10 loops each)
%%timeit -r 5 -n 10
test_fun1()
403 µs ± 31.3 µs per loop (mean ± std. dev. of 5 runs, 10 loops each)
%%timeit -r 10 -n 10
test_fun1()
329 µs ± 41.8 µs per loop (mean ± std. dev. of 10 runs, 10 loops each)
%%timeit -r 100 -n 10
test_fun1()
274 µs ± 62.8 µs per loop (mean ± std. dev. of 100 runs, 10 loops each)
- r = 1时,只运行一次,所以标准差为0
- r逐渐增大时,标准差会逐渐下降并趋于稳定
- 随着总次数的增加,平均最短时间也会降低(每10次求的一个最小执行时间)
- 当n逐渐变大
%%timeit -r 7 -n 1
test_fun1()
535 µs ± 286 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit -r 7 -n 2
test_fun1()
454 µs ± 139 µs per loop (mean ± std. dev. of 7 runs, 2 loops each)
%%timeit -r 7 -n 5
test_fun1()
417 µs ± 42.4 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)
%%timeit -r 7 -n 10
test_fun1()
383 µs ± 33.1 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit -r 7 -n 100
test_fun1()
281 µs ± 68.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
- 随着r增大,总次数增加,标准差也会减小
- r增大,平均值越接近于理论上的最快执行速度
- 所以日常使用的时候,如果你想看你的代码在一般情况下的运行速度,建议使用较小n;而如果想知道你代码逻辑的理论最快速度,应该用更大的n
- r = 1, n = 1, 时,等价于%%time
%%timeit -r 1 -n 1
test_fun1()
425 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
%%time
test_fun1()
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
Wall time: 429 µs