gpt4 book ai didi

python - Pandas:如何将 cProfile 输出存储在 Pandas DataFrame 中?

转载 作者:太空狗 更新时间:2023-10-30 00:09:24 25 4
gpt4 key购买 nike

已经有一些帖子讨论了使用 cProfile 进行 python 分析,以及分析输出的挑战,因为下面示例代码中的输出文件 restats 不是纯文本文件.下面的代码片段只是来自 docs.python.org/2/library/profile 的示例, 并且不可直接复制。

import cProfile
import re
cProfile.run('re.compile("foo|bar")', 'restats')

这里有一个讨论:Profile a python script using cProfile into an external file ,并在 docs.python.org 上有关如何使用 pstats.Stats 分析输出的更多详细信息(仍然只是示例,不可重现):

import pstats
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()

我可能在这里遗漏了一些非常重要的细节,但我真的很想将输出存储在 pandas DataFrame 中并从那里做进一步的分析。

我认为这会很简单,因为在 iPython 中运行 cProfile.run() 的输出看起来相当整洁:

In[]:
cProfile.run('re.compile("foo|bar")'

Out[]:

enter image description here

关于如何将其以相同格式放入 pandas DataFrame 有什么建议吗?

最佳答案

我知道这已经有了答案,但对于那些不想麻烦下载另一个模块的人来说,这里有一个粗略的现成脚本,应该接近了:

%%capture profile_results    ## uses %%capture magic to send stdout to variable
cProfile.run("your_function( **run_parms )")

首先运行上面的代码,用 stout 的内容填充 profile_results,其中包含 cProfile 的通常打印输出。

## Parse the stdout text and split it into a table
data=[]
started=False

for l in profile_results.stdout.split("\n"):
if not started:
if l==" ncalls tottime percall cumtime percall filename:lineno(function)":
started=True
data.append(l)
else:
data.append(l)
content=[]
for l in data:
fs = l.find(" ",8)
content.append(tuple([l[0:fs] , l[fs:fs+9], l[fs+9:fs+18], l[fs+18:fs+27], l[fs+27:fs+36], l[fs+36:]]))
prof_df = pd.DataFrame(content[1:], columns=content[0])

它不会因优雅或宜人的风格而赢得任何奖项,但它确实会将该结果表强制转换为可过滤的数据框格式。

prof_df 

enter image description here

关于python - Pandas:如何将 cProfile 输出存储在 Pandas DataFrame 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44302726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com