saving cProfile results to readable external file

后端 未结 5 1756
清酒与你
清酒与你 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:01

    Expanding upon the previous answer, you can dump everything out to a .csv file to sort and play around with in your favorite spreadsheet application.

    import pstats,StringIO
    
    # print stats to a string
    result=StringIO.StringIO()
    pstats.Stats(filename,stream=result).print_stats()
    result=result.getvalue()
    
    # chop the string into a csv-like buffer
    result='ncalls'+result.split('ncalls')[-1]
    result='\n'.join([','.join(line.rstrip().split(None,6)) for line in result.split('\n')])
    
    # save it to disk
    f=open(filename.rsplit('.')[0]+'.csv','w')
    f.write(result)
    f.close()
    

提交回复
热议问题