2011-10-03 9 views
3

나는 factorials를 생성하기 위해 파이썬에서 몇 가지 모듈을 썼다. 그리고 나는 실행 시간을 테스트하려고한다. 나는 here 프로파일의 예를 발견하고 내 모듈 프로필에 해당 템플릿을 사용 : 그러나파이썬 프로파일 링

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

답변

5

프로필러는 해석을 시도하는 문자열을받습니다. 문자열이 profile.run('fact(int(x)); print')이고 내부의 x 변수가 문자열의 일부일 뿐이며 변수로 해석 할 수 없습니다. 이 작업을 수행하려면 값을 문자열로 복사해야합니다. 이것을 시도하십시오 :

profile.run('fact(int(%s)); print' % x) 
profile.run('factMemoized(int(%s)); print' % x) 
+0

감사 @Constantinius보다 낫다! 나의 일부에 doh 순간이었다 :) – Craig

3

편집 (Petr Viktorin 's가 훨씬 더 잘 이해하는대로) 편집하십시오. 그러나 OP가 예상대로 작동하지 않는 이유에 대한 설명은 남겨 둡니다. profile.py (파이썬 2.7.2) 내가 클래스 프로필의 방법에 대해 다음 볼의 코드를 보면

:

def run(self, cmd): 
    import __main__ 
    dict = __main__.__dict__ 
    return self.runctx(cmd, dict, dict) 

def runctx(self, cmd, globals, locals): 
    self.set_cmd(cmd) 
    sys.setprofile(self.dispatcher) 
    try: 
     exec cmd in globals, locals 
    finally: 
     sys.setprofile(None) 
    return self 

runctx의 간부 인 성명() 전역에 모두 __main__.__dict__을 공급하고 있습니다 및 로컬 사전이므로 profile.run()은 실행중인 앱의 최상위 사전에 정의 된 변수 만 해결할 수 있습니다.

6

John Gaines Jr.가 말한 것처럼 profile.run()에는 범위 지정 문제가 있습니다. 그러나, 당신은()를 전역()과 지역 주민과 runctx을 사용할 수있는 명시 적 컨텍스트를 제공합니다

profile.runctx('fact(int(x)); print', globals(), locals()) 

노골적인 암시 :