Python分析

Cra*_*aig 4 python profiling

我在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()
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

知道我在这里做错了吗?TIA!〜克雷格

Pet*_*rin 7

正如John Gaines Jr.所说,profile.run()有一些范围问题.但是,您可以使用runctxglobals()和locals()并显式提供上下文:

profile.runctx('fact(int(x)); print', globals(), locals())
Run Code Online (Sandbox Code Playgroud)

明确比隐含更好:)


Con*_*ius 6

探查器接收一个他试图解释的字符串.你的字符串是profile.run('fact(int(x)); print'),而x里面的变量只是字符串的一部分,不能解析为变量.您必须将其值复制到字符串中才能使其工作.试试这个:

profile.run('fact(int(%s)); print' % x)
profile.run('factMemoized(int(%s)); print' % x)
Run Code Online (Sandbox Code Playgroud)