cProfile Examples in Python
Goal¶
This post aims to introduce how to use cProfile
to measure the running time for each statement and find the bottleneck of your program.
Libraries¶
import cProfile
Define your function¶
define your sub functions¶
def linear_func(n):
for i in range(n):
pass
return
def quad_func(n):
for i in range(n):
for i in range(n):
pass
return
def exp_func(n):
if n <= 1:
return n
return exp_func(n-1) + exp_func(n-2)
def main_func(n):
linear_func(n)
quad_func(n)
exp_func(n)
Profile the main function¶
cProfile.run('main_func(n=20)')
How to read the result¶
- ncalls is the number of calls.
- tottime is a total of the time spent.
- percall is the average time for each call, i.e., tottime divided by ncalls
- cumtime is the cumulative time spent.
- (2nd) percall is the quotient of cumtime divided by primitive calls
- filename:lineno(function) indicates the information about the function with the format "{file name}:{line number}{function name}"