Skip to content

Commit

Permalink
Add helper function for computing a duration from timeMethod output
Browse files Browse the repository at this point in the history
  • Loading branch information
isullivan committed Jan 30, 2025
1 parent 7536002 commit 25533b7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
32 changes: 31 additions & 1 deletion python/lsst/utils/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from __future__ import annotations

__all__ = ["profile", "logInfo", "timeMethod", "time_this"]
__all__ = ["duration_from_timeMethod", "profile", "logInfo", "timeMethod", "time_this"]

import datetime
import functools
Expand Down Expand Up @@ -479,3 +479,33 @@ def profile(filename: str | None, log: LsstLoggers | None = None) -> Iterator[cP
profile.dump_stats(filename)
if log is not None:
log.info("cProfile stats written to %s", filename)


def duration_from_timeMethod(
metadata: MutableMapping | None, method_name: str, clock: str = "Cpu"
) -> float | None:
"""Parse the metadata entries from ``timeMethod`` and return a duration
Parameters
----------
metadata : `collections.abc.MutableMapping`
The Task metadata that timing metrics were added to.
method_name : `str`
Name of the timed method to extract a duration for.
clock : `str`, optional
Options are "Cpu", "User", or "System"
Returns
-------
duration : `float`
The time elapsed between the start and end of the timed method.
"""
if metadata is None:
return None
start = metadata[method_name + "Start" + clock + "Time"]
if isinstance(start, list):
start = start[-1]
end = metadata[method_name + "End" + clock + "Time"]
if isinstance(end, list):
end = end[-1]
return end - start
5 changes: 4 additions & 1 deletion tests/test_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from dataclasses import dataclass

from astropy import units as u
from lsst.utils.timer import logInfo, logPairs, profile, time_this, timeMethod
from lsst.utils.timer import duration_from_timeMethod, logInfo, logPairs, profile, time_this, timeMethod

log = logging.getLogger("test_timer")

Expand Down Expand Up @@ -164,6 +164,9 @@ def testTaskLike(self):
with self.subTest(log=log, metadata=metadata):
task = Example1(log=log, metadata=metadata)
self.assertTimer(duration, task)
exampleDuration = duration_from_timeMethod(task.metadata, "sleeper")
if metadata is not None:
self.assertGreater(exampleDuration, 0)

def testDecorated(self):
"""Test timeMethod on non-Task like instances."""
Expand Down

0 comments on commit 25533b7

Please sign in to comment.