Profiling Python code using cProfile and generating an HTML report is a useful way to analyze the performance of your code and identify bottlenecks. To do this, you can use the cProfile
module to profile your Python script and then use a tool like pyprof2html
to convert the profiling data into an HTML report. Here’s how you can do it:
- First, ensure you have
cProfile
installed. It’s a standard Python library, so it should be available by default. - Install
pyprof2html
if you haven’t already. You can do this usingpip
:
pip install pyprof2html
Code language: Python (python)
- Create a Python script that you want to profile. For example, let’s say you have a script called
my_script.py
:
# my_script.py
def some_function():
for _ in range(1000000):
pass
def main():
some_function()
if __name__ == "__main__":
main()
Code language: Python (python)
- Profile your script using
cProfile
. You can do this from the command line:
python -m cProfile -o my_script_profile.prof my_script.py
Code language: Python (python)
This command will run your script with the cProfile
profiler, and the profiling data will be saved to a file named my_script_profile.prof
.
- Convert the profiling data to an HTML report using
pyprof2html
:
pyprof2html my_script_profile.prof
Code language: Python (python)
This command will generate an HTML report with the name my_script_profile.prof.html
.
- Open the HTML report in your web browser to analyze the profiling results:
xdg-open my_script_profile.prof.html # On Linux
open my_script_profile.prof.html # On macOS
start my_script_profile.prof.html # On Windows
Code language: Python (python)
You will see a detailed breakdown of function calls, their cumulative time, and more in the HTML report, helping you identify performance bottlenecks in your code.
That’s how you can use cProfile
and pyprof2html
to profile your Python code and generate an HTML report for performance analysis.
Read More;
- Python cProfiler Decorator [With Example]
- Python cProfile Multiprocessing With Example
- CProfileV: Making Python cProfile Usage Effortless
- Python cProfile Vs Timeit
- Python cProfile tottime vs cumtime
- Python cProfile With Arguments [With Example]
- Profile a Jupyter Notebook in Python
- Python cProfile Not Working [Solutions]
- Python cProfile Name is Not Defined (Fixed)
- Python cProfile ncalls With Examples
- Python cProfile Limit Depth
- Python cProfile Sort