Profiling Your Code with cProfile
We'll cover the following...
Profiling code with cProfile is really quite easy. All you need to do is import the module and call its run function. Let’s look at a simple example:
Press + to interact
import hashlibimport cProfilecProfile.run("hashlib.md5(b'abcdefghijkl').digest()")# 4 function calls in 0.000 CPU seconds# Ordered by: standard name# ncalls tottime percall cumtime percall filename:lineno(function)# 1 0.000 0.000 0.000 0.000 <string>:1(<module>)# 1 0.000 0.000 0.000 0.000 {_hashlib.openssl_md5}# 1 0.000 0.000 0.000 0.000 {method 'digest' of '_hashlib.HASH' objects}# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Here we import the hashlib module and use cProfile to profile the creation of an MD5 hash. The first line shows that there were 4 function calls. The next line tells us how the results are ordered. According to the documentation, standard name refers to the far right column. There are a number of columns here.
...
- ncalls is the number of calls made.
- tottime is a total of the time spent in the given function.
- percall refers to the quotient of tottime divided by ncalls
- cumtime