jos*_*eph 43 python command-line profiling file cprofile
我在名为bot4CA.py的模块上使用cProfile,因此在控制台中输入:
python -m cProfile -o thing.txt bot4CA.py
Run Code Online (Sandbox Code Playgroud)
模块运行并退出后,它会创建一个名为thing.txt的文件,当我打开它时,那里有一些信息,其余的是一堆乱七八糟的字符,而不是一个整齐有序的数据文件,这就是我想要的.有没有人知道如何使用cProfile并最终得到整齐有序的数据表,比如在命令行中正常使用它,除了在文件中?以下是.txt文件中某些数据的示例:
{( s) build\bdist.win32\egg\colorama\winterm.pyi' t reset_all( i i gpàÂs% ?geOÙHÌœE?{( s- build\bdist.win32\egg\colorama\ansitowin32.pyi¥
Run Code Online (Sandbox Code Playgroud)
我真正想要的是当您调用cProfile.run()时会发生什么,这会导致打印整齐有序的表格,显示所有功能的执行时间,而不是打印,保存在文件中,因为此程序相当大并且运行很多功能.
Eli*_*sky 61
您应该使用该pstats模块来解析此文件,并从中提取用户友好格式的信息.例如:
import pstats
p = pstats.Stats('thing.txt')
p.sort_stats('cumulative').print_stats(10)
Run Code Online (Sandbox Code Playgroud)
当然,这都在文档中.在那里阅读"即时用户手册",它解释了一切.
Tho*_*ner 16
直接丢弃统计信息:
echo 'stats' | python3 -m pstats path/to/cprofile_output_file
Run Code Online (Sandbox Code Playgroud)
pstats也有一个外壳
$ python3 -m pstats path/to/cprofile_output_file
Run Code Online (Sandbox Code Playgroud)
我们可以发出stats或发出sort这样的命令:
$ python3 -m pstats path/to/cprofile_output_file
Welcome to the profile statistics browser.
prof.txt% sort cumtime
prof.txt% reverse
prof.txt% stats
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 63:1(<module>)
1 0.000 0.000 0.000 0.000 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {built-in method builtins.print}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
prof.txt% ?
Documented commands (type help <topic>):
========================================
EOF add callees callers help quit read reverse sort stats strip
Run Code Online (Sandbox Code Playgroud)
我在这里喜欢的一个微功能是我可以自然地反转排序顺序<3
echo -e 'sort cumtime\nreverse\nstats' | python3 -m pstats path/to/cprofile_output_file
Run Code Online (Sandbox Code Playgroud)
wis*_*cky 10
其他答案更强大和灵活,但如果您只想获得快速输出,请使用>而不是-o. 这将以纯文本格式保存报告。
python -m cProfile myscript.py > cprofile.txt
python -m cProfile bot4CA.py > thing.txt
Run Code Online (Sandbox Code Playgroud)