【问题标题】:python - cProfile not runningpython - cProfile没有运行
【发布时间】:2012-07-03 11:48:39
【问题描述】:

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


    【解决方案1】:

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

    你可以试试吗

    import pstats
    

    如果显示无法导入 pstats,请尝试再次安装 python-profiler。它带有 python 本身,但如果 pstats 不存在,在你的情况下可能会搞砸。

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

    希望这会有所帮助!

    【讨论】:

    • 我试过导入pstats,但还是报同样的错误。 =[
    • 不,我的意思是尝试在 shell 中编写 import pstats。只需检查它是否存在,如果存在,那么您是否会收到其他错误。如果它导入成功,那么您需要查看模块是否还不错。在单独的文件中尝试docs.python.org/library/profile.html 中提到的一些用于 pstats 的功能(不在您的主代码中,只是为了检查 pstats 是否工作正常。)
    【解决方案2】:

    我今天在使用 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(...) 获得该文件名

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-06
      • 2020-01-24
      • 2018-12-05
      • 1970-01-01
      • 2021-09-02
      相关资源
      最近更新 更多