【问题标题】:Python profiling an inner functionPython分析内部函数
【发布时间】:2020-03-19 19:56:55
【问题描述】:

我正在尝试分析我的程序的一部分。模式如下:

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

当我试图运行这个程序时,我得到了一个错误: 文件“”,第 1 行,在 NameError: name 'abc' 未定义

有没有办法解决这个错误?

【问题讨论】:

  • run() 执行命令,而不是函数。
  • @jordanm 这不是命令吗?

标签: python cprofile


【解决方案1】:

在函数之外发生的一切,意味着它们在全局范围内是隐藏的。

使用 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()

输出:

"123"
5 function calls in 0.000 seconds

【讨论】:

    【解决方案2】:

    为了完整性:在你的情况下你也可以这样做

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

    (创建与runctx 变体相同的输出)

    【讨论】:

      猜你喜欢
      • 2013-09-08
      • 2011-07-19
      • 2012-08-18
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多