2011-12-30 40 views
4

我想我的函数中调用profile.run,即:的Python:变量的作用域和profile.run

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

然而,它说,调用run.profile当“X没有定义”。据我所知,我必须在调用run.profile的字符串参数中的g(x)之前提供import语句,并且可以使用全局变量来完成此操作。

这是可能的局部变量?

+0

简化版本的我的代码,显示该问题: '导入配置 DEF G(X) x = 0的 profile.run( 'G(X)') F( )' 但是,它显示“NameError:name'g'未定义”。 无论如何,这是同样的问题和profile.runctx解决了这个问题。感谢大家! – 2011-12-30 19:36:47

回答

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} 

>>> 

runctx()this document