我们如何记录python中大型管道中每个模块的时间花费。

时间:2018-05-02 12:38:18

标签: python logging profiling performance-testing

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

1 个答案:

答案 0 :(得分:0)

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