Sometimes, we want to profile a Python script.
In this article, we’ll look at how to profile a Python script.
How to profile a Python script?’
To profile a Python script, we can use the cProfile.run
method.
For instance, we write:
import cProfile
def hello():
print('hello')
cProfile.run('hello()')
We put the code into the string that we call cProfile.run
with to profile the hello
function’s execution.
Then we get output like:
5 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 <string>:1(<module>)
1 0.000 0.000 0.000 0.000 main.py:4(hello)
1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
printed on the screen.
Conclusion
To profile a Python script, we can use the cProfile.run
method.