17

我正在尝试将 cProfile 模块导入 Python 3.3.0,但出现以下错误:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    import cProfile
  File "/.../cProfile_try.py", line 12, in <module>
    help(cProfile.run)
AttributeError: 'module' object has no attribute 'run'

完整代码(cProfile_try.py)如下

import cProfile
help(cProfile.run)

L = list(range(10000000))
len(L)
# 10000000

def binary_search(L, v):
    """ (list, object) -> int

    Precondition: L is sorted from smallest to largest, and
    all the items in L can be compared to v.

    Return the index of the first occurrence of v in L, or
    return -1 if v is not in L.

    >>> binary_search([2, 3, 5, 7], 2)
    0
    >>> binary_search([2, 3, 5, 5], 5)
    2
    >>> binary_search([2, 3, 5, 7], 8)
    -1
    """

    b = 0
    e = len(L) - 1

    while b <= e:
        m = (b + e) // 2
        if L[m] < v:
            b = m + 1
        else:
            e = m - 1

    if b == len(L) or L[b] != v:
        return -1
    else:
        return b

cProfile.run('binary_search(L, 10000000)')
4

2 回答 2

34

如评论中所述,很可能意外存在一个名为 的文件profile.py,可能在当前目录中。无意中使用了此文件cProfile,从而掩盖了 Python 的profile模块。

建议的解决方案是:

mv profile.py profiler.py

接下来,为了更好的衡量,

如果使用 Python 3:

rm __pycache__/profile.*.pyc

如果使用 Python 2:

rm profile.pyc
于 2017-03-06T18:46:57.603 回答
-1

尝试使用“将配置文件导入为 cProfile”

于 2021-10-24T08:04:25.277 回答