使用%lsmagic
查看所有的内建magic comamnds
内建magic commands
%timeit
在任意一行代码前加%timeit
将对该行代码测速。
%timeit rand_nums = np.random.rand(1000)
使用-r
和-n
控制运行次数,每次循环次数。
%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)
对代码块测速
# Multiple lines of code
%%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)
将测速结果保存
times = %timeit -o rand_nums = np.random.rand(1000)
第三方magic command
line_profiler
用于性能分析,能得到每行代码的hit次数,运行时,运行时占比等。
安装
pip install line_profiler
使用
%load_ext line_profiler
%lrun -f func_name_to_profile func_name_to_profile(*args)
memory_profiler
用于内存分析
安装
pip install memory_profiler
使用
%load_ext memory_profiler
%mprun -f func_name_to_profile func_name_to_profile(*args)
Drawback
mprun
无法用于定义于ipython session内的函数,只能在外部模块中定义并import进来。