嵌套函数中使用cProfile

4

我正在尝试使用cProfile.run来分析一个嵌套函数。我明白也许cProfile并不在我调用它的同一作用域中运行,但我不太确定实现这一点的惯用方法是什么。以下是一个MVCE:

def foo():
    def bar():
        # do something here
        return 1
    cProfile.run('bar()')

产生错误:
NameError: name 'bar' is not defined
2个回答

3
使用 cProfile.runctx
def foo():
    def bar():
        # do something here
        return 1
    cProfile.runctx('bar()', None, locals=locals())

0

使用 cProfile.run

def foo():
    def bar():
        # do something here
        return 1
    cProfile.run(bar.__code__)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接