Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save output of cProfile.Profile() to a *.prof file in Python Script

Hi I know the usage of command line method to profile a python script as given below.

python -m cProfile -o program.prof my_program.py

However I'm profiling specific piece of code in Python using cProfile module as given below.

import cProfile, pstats, io
pr = cProfile.Profile()
pr.enable()
# ... do something ...
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())

How do I save pr the output of cProfile.Profile() to a *.profile file instead of using pstats.Stats() to analyze and print the profiling results. So I can use it to visually analyze the stats using SnakeViz or similar utilities.

like image 599
Muhammad Abdullah Avatar asked Dec 19 '17 08:12

Muhammad Abdullah


People also ask

How do you profile a Python code using cProfile?

The syntax is cProfile. run(statement, filename=None, sort=-1) . You can pass python code or a function name that you want to profile as a string to the statement argument. If you want to save the output in a file, it can be passed to the filename argument.


1 Answers

The Profile class has a method to write the stats to a file. You can use this to save the output to a file.

filename = 'profile.prof'  # You can change this if needed
pr.dump_stats(filename)
like image 74
Shailesh Avatar answered Oct 17 '22 05:10

Shailesh