【问题标题】:How can we log time spend by each module in a large pipeline in python.我们如何在 python 的大管道中记录每个模块花费的时间。
【发布时间】:2018-05-02 12:38:18
【问题描述】:

我有一个 python 管道代码,它调用大约 10 到 12 个 python 类。 我想知道并记录每个类中每个方法消耗的时间。 任何人都可以建议一些在python中执行此操作的方法 我正在使用 python 内置日志记录模块进行日志记录

【问题讨论】:

  • 合适的分析器在这里不是更好的工具吗?
  • 我已经尝试过探查器。我无法过滤分析器提供的整个输出,也无法记录它们。如果您能建议一些方法,我们可以过滤内置或库方法调用并记录我们编码的模块的时间和性能,那将非常有帮助。
  • Here 有一个如何使用装饰器的示例。
  • @Luis Muñoz。谢谢,它有效。唯一的问题是在每个py文件中导入方法并写入。出于我的好奇心,有一个错误的问题是,我们有什么方法可以在代码开始时调用一种函数方法,它会对整个代码库进行计时,而对代码的更改最少???
  • 我不知道,但应该有:)。继续挖掘装饰器,那里有很多魔法。

标签: python logging profiling performance-testing


【解决方案1】:
import logging
import time

class myClass():
    logErrors = False
    logger = None

    def log(self, msg):
        if self.logger != None:
            self.logger.warning(msg)

    def __init__(self, log=False):
        self.logErrors = log

        if self.logErrors == True:
            self.logger = logging.getLogger("myClass")
            self.logger.setLevel(logging.INFO)
            formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            self.ch = logging.StreamHandler()
            self.ch.setLevel(logging.INFO)
            self.ch.setFormatter(formatter)
            self.logger.addHandler(self.ch)


    def method1(self):
        # log start time of method
        self.log("method1() started")

        # code
        print("foobar")
        time.sleep(1)

        # log end time of method
        self.log("method1() ended")

my = myClass(log=True)
my.method1()

【讨论】:

  • 非常感谢您的努力。我们能否以这样一种方式做到这一点:一旦我们启动管道,它会自动记录(如分析器)而不是记录每个方法?我在整个代码库中有大约 50 多个方法如果我需要为每个模块添加时间将会非常痛苦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 1970-01-01
  • 2013-09-17
  • 1970-01-01
  • 2021-01-22
  • 2021-12-06
  • 1970-01-01
相关资源
最近更新 更多