saving cProfile results to readable external file

后端 未结 5 1764
清酒与你
清酒与你 2021-02-19 01:16

I am using cProfile try to profile my codes:

pr = cProfile.Profile()
pr.enable()
my_func()   # the code I want to profile
pr.disable()
pr.print_stat         


        
5条回答
  •  南旧
    南旧 (楼主)
    2021-02-19 02:00

    You can run the profiler saving the output into a file, as you do:

    import cProfile
    
    cProfile.run('my_func()', 'profile_results')
    

    And then format that result using the class pstats.Stats (https://docs.python.org/3/library/profile.html#the-stats-class):

    import pstats
    
    file = open('formatted_profile.txt', 'w')
    profile = pstats.Stats('.\profile_results', stream=file)
    profile.sort_stats('cumulative') # Sorts the result according to the supplied criteria
    profile.print_stats(15) # Prints the first 15 lines of the sorted report
    file.close()
    

提交回复
热议问题