Stu*_*urK 4 python variables profile scope
我想在我的函数中调用profile.run,即:
def g():
    ...
def f():
    x = ...
    run.profile('g(x)')
但是,在调用run.profile时,它表示"x未定义".据我所知,我必须在调用run.profile的字符串参数中的g(x)之前提供import语句,我可以使用全局变量来完成此操作.
这可能与局部变量有关吗?
Ada*_*man 16
而不是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()于本文件.
不必x设置函数的参数,而是x包含整个函数调用。
例子:
import cProfile
def g(x):
    print x
x = """g("Hello world!")"""
cProfile.run(x)