嵌套函数中的 cProfile

cProfile inside a nested function

我正在尝试使用 cProfile.run 分析嵌套函数。我知道 cProfile 可能与我调用它的范围不在 运行 范围内,但我不太确定实现这一目标的惯用方法是什么。这是一个 MVCE:

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

报错:

NameError: name 'bar' is not defined

使用cProfile.runctx:

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

使用cProfile.run

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