Search code examples
pythoncprofilepstats

How to use "dump_pstats" properly to retrieve the sorted data of the "cProfile" into "txt" file?


As the title indicate I have this issue of retrieving those information from dump_stats properly. Without further ado here is my simple code.

Code

import cProfile
import pstats

def fun_to_profile():
    ... code to be profilled ...

profiler = cProfile.Profile()

profiler.runcall(fun_to)profile)

stats.sort_stats('cumulative')

stats.print_stats()

stats.dump_stats("output.txt")

This is the simple code that I could found, and I really read multiple times the documentation.

Problem

My problem when I open the file "output.txt", even if it's empty or with non comprehended characters. So do I need to specify any extension of the file, or maybe the issue is with my compiler.

Thanks in advance.


Solution

  • Apparently working with cProfile is so easy and straight forwards. I figure the solution for the problem.

    First of all we need to know that the more adequate file extension is "file.dat". Then we need to read it and writing down in the desired files format like text.txt.

    For that we need the following piece of code :

    import cProfile
    import pstats   
    cProfile.run("fun_to_profile", "Out_put_profile.dat") # here we just run and save the output
    with open("Profile_time.txt", "w") as f:
    p = pstats.Stats("Out_put_profile.dat", stream=f)
    p.sort_stats("time").print_stats() # here we sort our analysis by the time-spent 
    

    And just like this we will have a more materials for analyzing the code and in human readable format. Thanks for IDG TECHtalk for sharing the solution. Link to the youtube video: https://youtu.be/dmnA3axZ3FY.