contextlib.contextmanager を使って適当にやる
from __future__ import annotations
from contextlib import contextmanager
from datetime import datetime
from logging import Logger
import time
from typing import Generator
@contextmanager
def timer(
name: str,
logger: Logger | None = None,
log_start: bool = False,
) -> Generator:
start = time.time()
if log_start:
start_str = datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S')
msg = f'{name} started at {start_str}'
if logger:
logger.info(msg)
else:
print(msg)
yield
seconds = time.time() - start
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(int(minutes), 60)
days, hours = divmod(hours, 24)
msg = f'{name} took '
if days:
msg += f'{days} days, {hours} hours, {minutes} minutes'
elif hours:
msg += f'{hours} hours, {minutes} minutes, {seconds:.0f} seconds'
elif minutes:
msg += f'{minutes} minutes, {seconds:.0f} seconds'
else:
msg += f'{seconds:.2f} seconds'
if logger:
logger.info(msg)
else:
print(msg)
使い方
with timer('foo'):
time.sleep(1)
コメント