Tips&Tricks

Python 3 performance profiling – easiest way

python logo

Just add cProfile module to the running command:

python3 -m cProfile test.py

For example:

$ python3 -m cProfile test.py
14 function calls in 0.000 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 test.py:1()
10 0.000 0.000 0.000 0.000 test.py:1(func)
1 0.000 0.000 0.000 0.000 test.py:4()
1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}

Profiling is a form of dynamic program analysis that measures, for example, the space (memory) or time complexity of a program, the usage of particular instructions, or the frequency and duration of function calls. Most commonly, profiling information serves to aid program optimization.

In this example we can see how many times each function called. Also it shows how long it was (for each function). So we can understand which part of the code we should optimize.