簡體   English   中英

Python 統計信息:如何將其寫入(人類可讀的)文件

[英]Python stats: how do I write it to a (human readable) file

我正在使用 Python 的 hotshot 分析器: http : //docs.python.org/2/library/hotshot.html

它顯示了如何打印統計信息:

stats.print_stats(20)

但是我怎么把它放到一個文件中呢? 我不確定如何獲取信息,以便我可以使用 write() 將其寫入文件。

編輯:

我想要以這種方式打印的相同易於閱讀的結果:

stats = hotshot.stats.load("stones.prof")
stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats(20) 

所以它看起來像這樣:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1    3.295    3.295   10.090   10.090 pystone.py:79(Proc0)

(所以當我打開stones.prof 時它看起來不像)

Stats采用可選的“stream”參數。 只需打開一個文件並將打開的文件對象傳遞給Stats構造函數,如下所示。 從那時起,對print_stats()的任何調用都將輸出到傳遞給構造函數的流中。 希望這可以幫助。 :)

with open('path/to/output', 'w') as stream:
    stats = pstats.Stats('path/to/input', stream=stream)
    stats.print_stats()

輸出重定向怎么樣?

import sys
import pstats
sys.stdout = open('readable.profile', 'w')
p = pstats.Stats('input.profile')
p.print_stats()

我最終重寫了print_stats()函數,從pstats.py復制它。 它返回一個字符串,然后可以將其寫入文件。 我沒有測試過每個if-else循環,只是它在我需要的示例中工作。 我留下原來的線條注釋掉了。 我已經將變量名稱保持不變,盡管它不再是函數正在使用的“自我”。

stats = hotshot.stats.load("stones.prof")
stats.strip_dirs()
stats.sort_stats('time', 'calls')
readable_str = xprint_stats(stats, 20)

import pstats
def xprint_stats(self, *amount):
    x = ""
    for filename in self.files:
        x += " " + filename
    #if self.files: print >> self.stream
    # ?
    indent = ' ' * 8
    for func in self.top_level:
        #print >> self.stream, indent, xfunc_get_function_name(func)
        x += indent + pstats.func_get_function_name(func)

    #print >> self.stream, indent, self.total_calls, "function calls",
    x +=  indent + str(self.total_calls) + " function calls" + " "
    if self.total_calls != self.prim_calls:
        #print >> self.stream, "(%d primitive calls)" % self.prim_calls,
        x += "(%d primitive calls)" % self.prim_calls + " "
    #print >> self.stream, "in %.3f seconds" % self.total_tt
    #print >> self.stream
    x +=  "in %.3f seconds" % self.total_tt + "\n"
    #width, list = stats.get_print_list(amount)
    msg, width, list = xget_print_list(stats, amount)
    x += msg

    if list:
        #self.print_title()
        x += "\n" + '   ncalls  tottime  percall  cumtime  percall filename:lineno(function)'
        x += "\n"
        for func in list:
            #self.print_line(func)
            x +=  xprint_line(self, func) + "\n"
#        print >> self.stream
#        print >> self.stream
    #return self
    return x

def xprint_line(self, func):  
    x = ""
    cc, nc, tt, ct, callers = self.stats[func]
    c = str(nc)
    if nc != cc:
        c = c + '/' + str(cc)
#    print >> self.stream, c.rjust(9),
#    print >> self.stream, f8(tt),
    x +=  c.rjust(9) + " "
    x +=  pstats.f8(tt) + " "
    if nc == 0:
        #print >> self.stream, ' '*8,
       x +=  ' '*8 
    else:
        #print >> self.stream, f8(float(tt)/nc),
        x +=  pstats.f8(float(tt)/nc) + " "
    #print >> self.stream, f8(ct),
    x +=  pstats.f8(ct) + " "
    if cc == 0:
        #print >> self.stream, ' '*8,
        x +=  ' '*8
    else:
        #print >> self.stream, f8(float(ct)/cc),
        x +=   pstats.f8(float(ct)/cc) + " "
    #print >> self.stream, func_std_string(func)
    x +=  pstats.func_std_string(func) + " "
    return x

def xget_print_list(self, sel_list):
    width = self.max_name_len
    if self.fcn_list:
        stat_list = self.fcn_list[:]
        msg = "   Ordered by: " + self.sort_type + '\n'
    else:
        stat_list = self.stats.keys()
        msg = "   Random listing order was used\n"

    for selection in sel_list:
        stat_list, msg = self.eval_print_amount(selection, stat_list, msg)

    count = len(stat_list)

    if not stat_list:
        return 0, stat_list
    #print >> self.stream, msg
    if count < len(self.stats):
        width = 0
        for func in stat_list:
            if  len(pstats.func_std_string(func)) > width:
                width = len(pstats.func_std_string(func))
    #return width+2, stat_list
    return msg, width+2, stat_list

您可以使用該庫:pstats_print2list https://pypi.python.org/pypi/pstats_print2list

pip install pstats_print2list和用法:

from pstats_print2list import get_pstats_print2list, print_pstats_list
fname_stats = 'my_profiling_out.stats'
pstats_list = get_pstats_print2list(
    os.path.expanduser(fname_stats),
    filter_fnames=['myfile1.py', 'myfile2.py', 'root_path1'],
    exclude_fnames=['dontshow.py', 'path_dont_show'],
    sort='cumulative',
    limit=5,
)
print_pstats_list(pstats_list)

對於那些正在尋找另一種解決方案的人,我們可以將字符串數據放入 txt 文件中。 下面的代碼將使用兩個函數將兩個數字相加,然后制作 Profile 數據,最后將其寫入一個 out.txt 文件。

主文件

import cProfile
import time
import pstats
from io import StringIO

def add_slow(a, b):
    time.sleep(0.5)
    return a+b

def add_fast(a, b):
    return a+b

prof = cProfile.Profile()

def main_func():
    arr = []
    prof.enable()
    for i in range(10):
        if i%2==0:
            arr.append(add_slow(i,i))
        else:
            arr.append(add_fast(i,i))
    prof.disable()
    #prof.print_stats(sort='time')
    prof.dump_stats("main_funcs.prof")
    return arr

main_func()
stream = StringIO();
stats = pstats.Stats("main_funcs.prof", stream=stream); 
stats.print_stats()
stream.seek(0)
print(16*'=',"RESULTS",16*'=')
data = stream.read()
print(data)
myText = open('out.txt', 'w')
myText.write(data)
myText.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM