简体   繁体   中英

Python profiling an inner function

I am trying to profile a part of my program. The pattern is like the following:

def de():
      def abc():
         print("123")
      cProfile.run('abc()')

When I am trying to run this program, I got an error: File "", line 1, in NameError: name 'abc' is not defined

Is there anyway to work around this error?

Everything happening outside of the function, meaning that they are hidden from the global scope.

use runctx(). Please read https://docs.python.org/3/library/profile.html#profile.runctx

import cProfile

def de():
      def abc():
         print("123")
      cProfile.runctx('abc()', None, locals=locals())

de()

output:

"123"
5 function calls in 0.000 seconds

Just for completeness: in your case you could also do

def de():
    def abc():
        print("123")
    cProfile.run(abc.__code__)

de()

(creates the same output as the runctx variant)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM