OneRaynyDay
OneRaynyDay

Reputation: 3968

cProfile inside a nested function

I am trying to profile a nested function using cProfile.run. I understand that perhaps cProfile isn't running at the same scope as where I am calling it, but I'm not quite sure what the idiomatic way to achieve this is. Here's an MVCE:

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

Gives the error:

NameError: name 'bar' is not defined

Upvotes: 4

Views: 814

Answers (2)

sandes
sandes

Reputation: 2267

Using cProfile.run

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

Upvotes: 0

MoxieBall
MoxieBall

Reputation: 1916

Use cProfile.runctx:

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

Upvotes: 3

Related Questions