python - cProfile没有运行

问题描述 投票:6回答:2

我试图使用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>''

有人可以帮我调试这个,希望能提供解决方案吗?

我在Wing IDE 101 ver4.1上运行Python 2.7.3。

谢谢!!!

python cprofile
2个回答
3
投票

这似乎是pStats模块的问题,而不是cProfile。

你能尝试做吗?

import pstats

如果这说不能导入pstats,那么再次尝试安装python-profiler。它带有python本身,但如果pstats不存在,可能会在你的情况下搞砸了。

这是一个简单的apt-get on linux,所以我假设windows也有一个单独的二进制文件用于python-profiler。

希望这可以帮助!


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(...)获得

© www.soinside.com 2019 - 2024. All rights reserved.