ves*_*and 6 python profiling pandas
已经存在一些讨论使用cProfile进行python分析的帖子,以及由于以下示例代码中的输出文件统计信息不是纯文本文件而导致的分析输出的挑战。下面的代码片段只是docs.python.org/2/library/profile中的一个示例,不能直接复制。
import cProfile
import re
cProfile.run('re.compile("foo|bar")', 'restats')
Run Code Online (Sandbox Code Playgroud)
这里有一个讨论:使用cProfile将python脚本分析到一个外部文件中,并且在docs.python.org上有更多有关如何使用pstats.Stats分析输出的详细信息(仍然只是一个示例,并且不可重现):
import pstats
p = pstats.Stats('restats')
p.strip_dirs().sort_stats(-1).print_stats()
Run Code Online (Sandbox Code Playgroud)
我可能在这里错过了一些非常重要的细节,但是我真的很想将输出存储在pandas DataFrame中并从那里做进一步的分析。
我认为这将非常简单,因为iPython运行中的输出cProfile.run()看起来很整洁:
In[]:
cProfile.run('re.compile("foo|bar")'
Out[]:
Run Code Online (Sandbox Code Playgroud)
关于如何以相同格式将其放入pandas DataFrame的任何建议?
我知道这已经有了答案,但是对于那些不想麻烦地下载另一个模块的人来说,这里有一个应该接近的粗略且准备好的脚本:
%%capture profile_results ## uses %%capture magic to send stdout to variable
cProfile.run("your_function( **run_parms )")
Run Code Online (Sandbox Code Playgroud)
首先运行上面的代码,以填充profile_resultsstout 的内容,其中包含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])
Run Code Online (Sandbox Code Playgroud)
它不会因优雅或令人愉快的风格而赢得任何奖项,但它确实迫使结果表转换为可过滤的数据框格式。
prof_df
Run Code Online (Sandbox Code Playgroud)
我知道这个问题有点老了,但我找到了一个简单的方法来解决它。
import cProfile
import pandas as pd
with cProfile.Profile() as pr:
# run something
df = pd.DataFrame(
pr.getstats(),
columns=['func', 'ncalls', 'ccalls', 'tottime', 'cumtime', 'callers']
)
Run Code Online (Sandbox Code Playgroud)
看起来https://github.com/ssanderson/pstats-view可能会执行您想要的操作(尽管与可视化数据并使其交互相关的不必要的依赖项):
>>> from pstatsviewer import StatsViewer
>>> sv = StatsViewer("/path/to/profile.stats")
>>> sv.timings.columns
Index(['lineno', 'ccalls', 'ncalls', 'tottime', 'cumtime'], dtype='object')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
722 次 |
| 最近记录: |