How do I profile a Python script?
There are several ways to profile a Python script:
- The
cProfile
module is a built-in library for profiling Python scripts. You can use it by running the following command:
python -m cProfile my_script.py
This will generate a report that shows the total time spent in each function and the number of times each function was called.
- The
profile
module is another built-in library for profiling Python scripts. You can use it by adding the following lines at the beginning of your script:
import profile
profile.run("my_function()")
Watch a video course
Python - The Practical Guide
Then, run your script as usual:
python my_script.py
This will generate a report that shows the total time spent in each function and the number of times each function was called.
The
pstats
module is a library for analyzing the results of profiling. You can use it to sort the profiling results by the total time spent in each function, or by the number of calls to each function.There are also several third-party libraries and tools that can be used for profiling Python scripts, such as
pyprof2calltree
,snakeviz
, andyappi
.