查看运行时间

高效编写 Python 代码

Logan Thomas

Scientific Software Technical Trainer, Enthought

为何要计时代码?

  • 帮助我们选择最优编码方式
  • 代码越快,效率越高!
高效编写 Python 代码

如何给代码计时?

  • 用 IPython 魔法命令 %timeit 计算运行时间

  • 魔法命令:对普通 Python 语法的增强

    • 以"%"开头
    • 文档链接(here
    • %lsmagic 查看所有魔法命令
高效编写 Python 代码

使用 %timeit

待计时时的代码

import numpy as np

rand_nums = np.random.rand(1000)

%timeit 计时

%timeit rand_nums = np.random.rand(1000)
8.61 µs ± 69.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
高效编写 Python 代码

%timeit 输出

alt="Magic 命令 timeit 的输出"

高效编写 Python 代码

%timeit 输出

alt="Magic 命令 timeit 的输出,高亮显示均值和标准差"

高效编写 Python 代码

%timeit 输出

alt="Magic 命令 timeit 的输出,高亮显示运行次数和循环次数"

高效编写 Python 代码

指定运行/循环次数

设置运行次数(-r)和/或循环次数(-n

# 将运行次数设为 2(-r2)
# 将循环次数设为 10(-n10)

%timeit -r2 -n10 rand_nums = np.random.rand(1000)
16.9 µs ± 5.14 µs per loop (mean ± std. dev. of 2 runs, 10 loops each)
高效编写 Python 代码

以行模式使用 %timeit

行魔法(%timeit

# 单行代码

%timeit nums = [x for x in range(10)]
914 ns ± 7.33 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
高效编写 Python 代码

以单元模式使用 %timeit

单元魔法(%%timeit

# 多行代码

%%timeit
nums = []
for x in range(10):
    nums.append(x)
1.17 µs ± 3.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
高效编写 Python 代码

保存输出

将输出保存到变量(-o

times = %timeit -o rand_nums = np.random.rand(1000)
8.69 µs ± 91.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
高效编写 Python 代码
times.timings
[8.697893059998023e-06,
 8.651204760008113e-06,
 8.634270530001232e-06,
 8.66847825998775e-06,
 8.619398139999247e-06,
 8.902550710008654e-06,
 8.633500570012985e-06]
times.best
8.619398139999247e-06
times.worst
8.902550710008654e-06
高效编写 Python 代码

比较时间

可用正式名称创建 Python 数据结构

formal_list = list()
formal_dict = dict()
formal_tuple = tuple()

也可用字面量语法创建 Python 数据结构

literal_list = []
literal_dict = {}
literal_tuple = ()
高效编写 Python 代码
f_time = %timeit -o formal_dict = dict()
145 ns ± 1.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
l_time = %timeit -o literal_dict = {}
93.3 ns ± 1.88 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
diff = (f_time.average - l_time.average) * (10**9)
print('l_time better than f_time by {} ns'.format(diff))
l_time better than f_time by 51.90819192857814 ns
高效编写 Python 代码

比较时间

%timeit formal_dict = dict()
145 ns ± 1.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%timeit literal_dict = {}
93.3 ns ± 1.88 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
高效编写 Python 代码

准备开跑!

高效编写 Python 代码

Preparing Video For Download...