2011-12-30 6 views
4

내 함수 내에서 profile.run 호출 할, 즉 : 그러나파이썬 : 변수 범위와 profile.run

def g(): 
    ... 
def f(): 
    x = ... 
    run.profile('g(x)') 

, 그것은 run.profile를 호출 할 때 'X가 정의되지 않은'말했다. 내가 아는 한, run.profile에 문자열 인자 안에 g (x)를 호출하기 전에 import 문을 제공해야하며 전역 변수를 사용하여이 작업을 수행 할 수 있습니다.

지역 변수를 사용할 수 있습니까?

+1

코드가없는 코드와 특정 오류 또는 추적을 표시하십시오. 문제를 도시 내 코드의 –

+0

감소 버전 : '수입 프로필 데프 g (X) : 패스 데프 F() : X = 0 profile.run ('g (X) ') F ()' 그러나 "NameError : name 'g'not defined"가 표시됩니다. 어쨌든, 그것은 같은 문제이며 profile.runctx가 문제를 해결합니다. 모두에게 감사드립니다! –

답변

1

x이 함수의 인수로 설정되는 대신 x에는 전체 함수 호출이 포함되어야합니다.

예 :

import cProfile 
def g(x): 
    print x 
x = """g("Hello world!")""" 
cProfile.run(x) 
12

대신이 지역 주민과 전역을 제공 할 수 있습니다 run() 사용 runctx()를 사용. 예를 들어 :

>>> import cProfile 
>>> def g(x): 
... print "g(%d)" % x 
... 
>>> x=100 
>>> cProfile.runctx('g(x)', {'x': x, 'g': g}, {}) 
g(100) 
     3 function calls in 0.000 CPU seconds 

    Ordered by: standard name 

    ncalls tottime percall cumtime percall filename:lineno(function) 
     1 0.000 0.000 0.000 0.000 <stdin>:1(g) 
     1 0.000 0.000 0.000 0.000 <string>:1(<module>) 
     1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 

>>> 

this documentrunctx() 참조하십시오.