如何测试python代码

Posted on Thu 25 October 2018 in programming

Profiling Python

Timeit

You can use timeit in IPython to time the statement.

timeit

Profiler

Say you have following python code:

import numpy as np

def solve():
    x = np.random.rand(10, 10)
    b = np.random.rand(10, 1)
    return np.linalg.solve(x, b)

if __name__ == '__main__':
    solve()

You can time the script using following code in ipython:

profile

You can also use python -m cProfile test.py to profile.

Line-profiler

  1. Use pip install line_profiler to install
  2. add @profile to decorate your function
  3. Use kernprof -l -v test.py to profile
import numpy as np

@profile
def solve():
    x = np.random.rand(10, 10)
    b = np.random.rand(10, 1)
    return np.linalg.solve(x, b)

if __name__ == '__main__':
    solve()

lineprofile

Reference

optimize python code line-profiler