我想在我的函数中调用 profile.run,即:
def g():
...
def f():
x = ...
run.profile('g(x)')
但是,它在调用 run.profile 时显示“x is not defined”。据我所知,我必须在调用 g(x) inside string argument 到 run.profile 之前提供 import 语句,我可以用全局变量来做到这一点。
局部变量是否可行?
最佳答案
不要使用 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 document 中的 runctx()
.
关于Python:变量范围和 profile.run,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8682716/