Python cProfile to HTML With Example

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:

  1. First, ensure you have cProfile installed. It’s a standard Python library, so it should be available by default.
  2. Install pyprof2html if you haven’t already. You can do this using pip:
pip install pyprof2htmlCode language: Python (python)
  1. 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)
  1. Profile your script using cProfile. You can do this from the command line:
python -m cProfile -o my_script_profile.prof my_script.pyCode 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.

  1. Convert the profiling data to an HTML report using pyprof2html:
pyprof2html my_script_profile.profCode language: Python (python)

This command will generate an HTML report with the name my_script_profile.prof.html.

  1. 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 WindowsCode 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;

  • Abdullah Walied Allama

    Abdullah Walied Allama is a driven programmer who earned his Bachelor's degree in Computer Science from Alexandria University's Faculty of Computer and Data Science. He is passionate about constructing problem-solving models and excels in various technical skills, including Python, data science, data analysis, Java, SQL, HTML, CSS, and JavaScript.

    View all posts

Leave a Comment