本文介绍如何使用ipython进行快速的实验和调试,闲话免谈,直接经过demo进入主题。python
在系统shell中执行cmdshell
In [35]: !ls Gemfile Gemfile.lock README.md Rakefile bin config db log src
将系统目录更改成directoryvim
In [36]: %cd - /private/tmp
在执行完代码,若是出现错误,当即执行%debug命令后将会进入调试器。在接触%debug以前,笔者都是使用的是pdb.set_trace来调试程序,这样的硬编码很是之不方便。dom
In [45]: !touch a.py In [46]: !vim a.py In [47]: !cat a.py def divide(): assert(1 == 0) divide() In [56]: %run a.py --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) /private/tmp/a.py in <module>() 2 assert(1 == 0) 3 ----> 4 divide() /private/tmp/a.py in divide() 1 def divide(): ----> 2 assert(1 == 0) 3 4 divide() AssertionError: In [57]: %debug > /private/tmp/a.py(2)divide() 1 def divide(): ----> 2 assert(1 == 0) 3 4 divide()
一样当即进入调试器。ide
用来测试各个部分或者函数的执行时间,它会自动屡次执行以产生一个很是精确的平均执行时间。函数
In [12]: strings = ['foo', 'foobar', 'baz','qux', '123 ffd'] * 100000
In [13]: %timeit method1 = [x for x in strings if x.startswith('foo')] 10 loops, best of 3: 93.4 ms per loop
In [14]: %timeit method2 = [x for x in strings if x[:3] == 'foo'] 10 loops, best of 3: 36.4 ms per loop
method2 比 method1 的性能要快两倍以上。工具
python的主要性能分析工具是cProfile模块,它会记录各个函数的耗费时间,在命令行中,能够经过以下命令来进行性能分析:oop
python -m cProfile xxx.py
而在ipython中,会使用下面的命令来运行一个文件性能
%run -p -s cumulative xxx.py
若是想要运行一个函数或语句,请使用以下命令:测试
%prun -l 7 -s cumulative run()
待测函数:
In [17]: from numpy.random import randn In [18]: x = randn(3000, 3000) In [19]: y = randn(3000, 3000) In [20]: def add_and_sum(x,y): ...: added = x + y ...: summed = added.sum(axis=1) ...: return summed ...:
使用prun的结果以下:
In [21]: %prun add_and_sum(x, y) 6 function calls in 0.340 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.310 0.310 0.335 0.335 <ipython-input-16-fbadffca33af>:1(add_and_sum) 1 0.025 0.025 0.025 0.025 {method 'reduce' of 'numpy.ufunc' objects} 1 0.005 0.005 0.340 0.340 <string>:1(<module>) 1 0.000 0.000 0.025 0.025 {method 'sum' of 'numpy.ndarray' objects} 1 0.000 0.000 0.025 0.025 _methods.py:31(_sum) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
上面的结果不是很好理解,笔者更喜欢用line_profiler库来分析。
使用一个库line_profiler,这个库的输出结果简单易理解。
这个库不是内建的,须要手动安装,安装命令:
pip install line_profiler
而后在ipython中手动load lprun:
In [2]: %load_ext line_profiler In [3]: %lprun Timer unit: 1e-06 s
待测函数:
In [17]: from numpy.random import randn In [18]: x = randn(3000, 3000) In [19]: y = randn(3000, 3000) In [20]: def add_and_sum(x,y): ...: added = x + y ...: summed = added.sum(axis=1) ...: return summed ...: In [21]: def call_function(): ...: x = randn(1000, 1000) ...: y = randn(1000, 1000) ...: return add_and_sum(x, y)
使用lprun后的结果以下:
In [23]: %lprun -f add_and_sum -f call_function call_function() Timer unit: 1e-06 s Total time: 0.004438 s File: <ipython-input-16-fbadffca33af> Function: add_and_sum at line 1 Line # Hits Time Per Hit % Time Line Contents ============================================================== 1 def add_and_sum(x,y): 2 1 3929 3929.0 88.5 added = x + y 3 1 508 508.0 11.4 summed = added.sum(axis=1) 4 1 1 1.0 0.0 return summed Total time: 0.062512 s File: <ipython-input-17-b03b81a6d2ba> Function: call_function at line 1 Line # Hits Time Per Hit % Time Line Contents ============================================================== 1 def call_function(): 2 1 29193 29193.0 46.7 x = randn(1000, 1000) 3 1 28449 28449.0 45.5 y = randn(1000, 1000) 4 1 4870 4870.0 7.8 return add_and_sum(x, y)
一般,会使用%prun(cProfile)作“宏观”性能分析,而用%lprun(line_profiler)作“微观”性能分析。使用line_profiler必需要指定待测的函数,是由于这个库要跟踪每一行代码的执行时间。
在一个变量的前面或后面加上问号?,能够显示该变量的基本信息
In [23]: a=1 In [24]: a? Type: int String form: 1 Docstring: int(x=0) -> int or long int(x, base=10) -> int or long >>> int('0b100', base=0) 4
若是这个变量是函数的话,一个问号?来显示docstring,两个问号来显示该函数的源码
检测python语句的执行时间
In [16]: %timeit sum(i*i for i in xrange(1000)) 10000 loops, best of 3: 68.6 µs per loop
执行这个命令,开始记录控制台会话,这样能够将整个过程保存起来