嵌套函数内的cProfile

时间:2018-06-25 17:59:36

标签: python cprofile

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

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

给出错误:

NameError: name 'bar' is not defined

2 个答案:

答案 0 :(得分:3)

使用cProfile.runctx

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

答案 1 :(得分:0)

使用cProfile.run

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