import time
from logging import Logger

import humanize


class Timer:
    """ 计时器 """
    def __init__(self, title: str, logger: Logger):
        self.title = title
        self.logger = logger
        self.start_at = 0
        self.start_cpu_at = 0
        self.cost = 0
        self.cpu_cost = 0

    def __enter__(self):
        self.start_at = time.time()
        self.start_cpu_at = time.process_time()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.cost = time.time() - self.start_at
        self.cpu_cost = time.process_time() - self.start_cpu_at
        self.logger.debug(
            f"{self.title}"
            f"执行时间: {humanize.naturaldelta(self.cost)}({self.cost:.2f}秒), "
            f"CPU运行时间: {humanize.naturaldelta(self.cpu_cost)}({self.cpu_cost:.2f}秒)"
        )
        if exc_type:
            raise exc_value
        return self
