简体   繁体   English

Python 分析内部函数

[英]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当我尝试运行此程序时,出现错误: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().使用 runctx()。 Please read https://docs.python.org/3/library/profile.html#profile.runctx请阅读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) (创建与runctx变体相同的输出)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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