Skip to content

Commit

Permalink
add timers
Browse files Browse the repository at this point in the history
  • Loading branch information
b8raoult committed Oct 25, 2024
1 parent c6a2130 commit e219eb5
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/anemoi/utils/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import logging
import time
from collections import defaultdict

from .humanize import seconds_to_human

Expand All @@ -35,3 +36,39 @@ def elapsed(self):

def __exit__(self, *args):
self.logger.info("%s: %s.", self.title, seconds_to_human(self.elapsed))


class _Timer:
"""Internal timer class."""

def __init__(self):
self.elapsed = 0.0

def __enter__(self):
self.start()
return self

def __exit__(self, *args):
self.stop()

def start(self):
self._start = time.time()

def stop(self):
self.elapsed += time.time() - self._start


class Timers:
"""A collection of timers."""

def __init__(self, logger=LOGGER):
self.logger = logger
self.timers = defaultdict(_Timer)

def __getitem__(self, name):
return self.timers[name]

def report(self):
length = max(len(name) for name in self.timers)
for name, timer in sorted(self.timers.items()):
self.logger.info("%s: %s.", f"{name:<{length}}", seconds_to_human(timer.elapsed))

0 comments on commit e219eb5

Please sign in to comment.