Python - cProfile运行不起来。

6

我尝试使用cProfile对我的代码进行性能测试,但不幸的是,无论我如何尝试,cProfile都无法正常运行。

以下是我所做的:

import cProfile
cProfile.run('addNum()')  # addNum() is a very simple function that adds a bunch of 
                          # numbers into a dictionary

这是我得到的结果:

Traceback (most recent call last):
File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Python27\Lib\cProfile.py", line 36, in run
result = prof.print_stats(sort)
File "C:\Python27\Lib\cProfile.py", line 81, in print_stats
pstats.Stats(self).strip_dirs().sort_stats(sort).print_stats()
File "C:\Python27\Lib\pstats.py", line 81, in __init__
self.init(arg)
File "C:\Python27\Lib\pstats.py", line 95, in init
self.load_stats(arg)
File "C:\Python27\Lib\pstats.py", line 124, in load_stats
self.__class__, arg)
TypeError: Cannot create or construct a <class pstats.Stats at 0x01AE9CA8> object from '<cProfile.Profile object at 0x01ACC470>''

有人能帮我调试一下吗,最好能提供解决方案?

我正在运行Python 2.7.3,并使用Wing IDE 101 ver4.1。

谢谢!

2个回答

2
这似乎是pStats模块的问题,而不是cProfile的问题。您可以尝试执行以下操作:
import pstats

如果出现“无法导入pstats”错误,那么请尝试重新安装python-profiler。虽然它是随着Python一起安装的,但如果缺少pstats,则可能会出现混乱的情况。
在Linux上,apt-get命令就可以轻松解决问题,因此我假设Windows也有一个独立的二进制文件用于安装python-profiler。
希望能对您有所帮助!

我已经尝试导入pstats,但它仍然报告相同的错误。 =[ - turtlesoup
1
不,我的意思只是在shell中尝试编写import pstats。只需检查它是否存在,如果存在,则需要查看是否会出现其他错误。如果成功导入,则需要查看模块是否有问题。在单独的文件中尝试一些在此处提到的pstats函数(不要在主代码中进行尝试,只是为了检查pstats是否正常工作)。请参阅http://docs.python.org/library/profile.html。 - user723556

0

我今天在Python 3.5.2中遇到了同样的问题:

最终解决方法是将我想要进行性能分析的调用替换为以下内容,然后运行整个程序:

import cProfile
# myObject.myFunc()
cProfile.runctx('myObject.myFunc()', globals(), locals(), 'myFunc.stat')

最后,在一个独立运行的交互式 python3 中,我执行了以下操作:

>>> import pstats
>>> p = pstats.Stats('myFunc.stat')
>>> p.strip_dirs().sort_stats(-1).print_stats()
Wed Feb 20 17:10:05 2019    myFunc.stat

         10218759 function calls (3916491 primitive calls) in 16.519 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   16.519   16.519 <string>:1(<module>)
   ... the really useful stats followed here ...

cProfile.runctx(...)globals()locals()是必要的,以解决我遇到的NameError问题;你问到的TypeError则通过指定一个文件名来存储统计信息得以解决,这个方法也可以通过普通的cProfile.run(...)实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接