cProfile 保存数据到文件导致字符混乱

76 投票
3 回答
59683 浏览
提问于 2025-04-17 07:08

我在一个叫做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()时的结果,这样会打印出一个整齐的表格,显示所有函数的执行时间,但我希望的是把这个表格保存到文件里,因为这个程序比较大,运行了很多函数。

3 个回答

10

其他的回答虽然更强大、更灵活,但如果你只是想快速得到一个输出,可以用 > 代替 -o。这样会把报告保存为普通文本格式。

python -m cProfile myscript.py > cprofile.txt
python -m cProfile bot4CA.py > thing.txt
72

直接输出统计信息:

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
95

你应该使用 pstats 模块来解析这个文件,并从中提取出易于理解的信息。例如:

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

当然,所有内容都在 文档中。你可以看看里面的“快速用户手册”,它会解释所有的内容。

撰写回答