我用Python写了几个模块来生成阶乘,现在想测试一下运行时间。我在这里找到了一个性能分析的例子,并使用该模板对我的模块进行了性能分析:
import profile #fact
def main():
x = raw_input("Enter number: ")
profile.run('fact(int(x)); print')
profile.run('factMemoized(int(x)); print')
def fact(x):
if x == 0: return 1
elif x < 2: return x
else:
return x * fact(x-1)
def factMemoized(x):
if x == 0: return 1
elif x < 2: return x
dict1 = dict()
dict1[0] = 1
dict1[1] = 1
for i in range (0, x+1):
if dict1.has_key(i): pass
else: dict1[i] = i * dict1[i-1]
return dict1[x]
if __name__ == "__main__":
main()
然而,我遇到了以下错误:
Enter number: 10
Traceback (most recent call last):
File "fact.py", line 32, in <module>
main()
File "fact.py", line 7, in main
profile.run('fact(int(x)); x')
File "C:\Python27\lib\profile.py", line 70, in run
prof = prof.run(statement)
File "C:\Python27\lib\profile.py", line 447, in run
return self.runctx(cmd, dict, dict)
File "C:\Python27\lib\profile.py", line 453, in runctx
exec cmd in globals, locals
File "<string>", line 1, in <module>
NameError: name 'x' is not defined
请问这里我做错了什么?谢谢! ~ craig