67

我在名为 bot4CA.py 的模块上使用 cProfile,所以在控制台中我输入:

python -m cProfile -o thing.txt bot4CA.py

模块运行并退出后,它会创建一个名为 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¥

我真正想要的是当您调用 cProfile.run() 时会发生什么,这会打印出一个组织整齐的表格,显示所有函数的执行时间,除了打印之外,保存在一个文件中,因为这个程序相当大并且运行很多的功能。

4

3 回答 3

83

您应该使用该pstats模块来解析此文件并从中提取用户友好格式的信息。例如:

import pstats
p = pstats.Stats('thing.txt')
p.sort_stats('cumulative').print_stats(10)

当然,这一切都在文档中。翻阅那里的“即时用户手册”,它解释了一切。

于 2011-11-27T03:03:29.997 回答
51

直接转储统计数据:

echo 'stats' | python3 -m pstats path/to/cprofile_output_file

pstats 也有一个外壳

$ python3 -m pstats path/to/cprofile_output_file

在里面我们可以像这样发出statssort命令:

$ 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

我在这里喜欢的一个微功能是我可以本地反转排序顺序<3

echo -e 'sort cumtime\nreverse\nstats' | python3 -m pstats path/to/cprofile_output_file
于 2018-11-15T08:38:05.760 回答
1

其他答案更强大、更灵活,但如果您只想获得快速输出,请使用>而不是-o. 这将以纯文本格式保存报告。

python -m cProfile myscript.py > cprofile.txt
python -m cProfile bot4CA.py > thing.txt
于 2021-10-07T22:29:55.310 回答