我试图将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'
Run Code Online (Sandbox Code Playgroud)
完整的代码(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)')
Run Code Online (Sandbox Code Playgroud)
Acu*_*nus 28
正如评论中所指出的,可能存在一个名为的文件profile.py,可能在当前目录中.这个文件被无意中使用cProfile,从而掩盖了Python的profile模块.
建议的解决方案是:
mv profile.py profiler.py
Run Code Online (Sandbox Code Playgroud)
接下来,为了更好的衡量,
如果使用Python 3:
rm __pycache__/profile.*.pyc
Run Code Online (Sandbox Code Playgroud)
如果使用Python 2:
rm profile.pyc
Run Code Online (Sandbox Code Playgroud)