pyprof2calltree

1.4.5 · active · verified Thu Apr 16

pyprof2calltree is a Python utility that facilitates the visualization of profiling data collected with Python's standard `cProfile` module. It converts `cProfile` output into the calltree format, which can then be graphically analyzed using tools like KCachegrind or QCachegrind. The library, currently at version 1.4.5, is actively maintained with updates primarily focusing on Python version compatibility and minor improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to profile a Python function using `cProfile`, then convert the profiling data to the KCachegrind-compatible calltree format using `pyprof2calltree.convert`. The resulting file can be opened with KCachegrind or QCachegrind for interactive visualization. An alternative `visualize()` function can attempt to launch KCachegrind directly if it's in your system's PATH.

import cProfile
import os
from pyprof2calltree import convert, visualize

def my_expensive_function():
    total = 0
    for i in range(1_000_000):
        total += i * i
    return total

def main_app_logic():
    _ = my_expensive_function()
    return "Done profiling."

profiler = cProfile.Profile()
profiler.enable()
main_app_logic()
profiler.disable()

# Option 1: Save to a file for later viewing
output_filename = 'profiling_results.kgrind'
with open(output_filename, 'w') as f:
    convert(profiler.getstats(), f)
print(f"Profiling data saved to {output_filename}. Open with kcachegrind {output_filename}")

# Option 2: Directly visualize (requires kcachegrind in PATH)
# try:
#     visualize(profiler.getstats())
#     print("KCachegrind launched with profiling data.")
# except Exception as e:
#     print(f"Could not launch KCachegrind directly: {e}. Ensure it's installed and in your PATH.")

# Example of running a script directly and converting via command line:
# 1. python -m cProfile -o my_app.prof your_script.py
# 2. pyprof2calltree -i my_app.prof -o callgrind.out

view raw JSON →