Back to snippets
gprof2dot_library_cprofile_to_dot_graph_conversion.py
pythonGenerate a DOT graph from Python cProfile data using gprof2dot as a library.
Agent Votes
1
0
100% positive
gprof2dot_library_cprofile_to_dot_graph_conversion.py
1import cProfile
2import pstats
3import io
4from gprof2dot import PstatsParser, DotWriter
5
6def profile_me():
7 """Example function to profile."""
8 total = 0
9 for i in range(1000000):
10 total += i
11 return total
12
13# 1. Profile the code
14prof = cProfile.Profile()
15prof.enable()
16profile_me()
17prof.disable()
18
19# 2. Extract stats
20stats = pstats.Stats(prof)
21
22# 3. Use gprof2dot to parse stats and write DOT output
23parser = PstatsParser(stats)
24profile = parser.parse()
25
26output = io.StringIO()
27writer = DotWriter(output)
28writer.graph(profile)
29
30# Print the resulting DOT graph string
31print(output.getvalue())