Skip to content

Timing

amltk.profiling.timing #

Module for timing things.

Timer dataclass #

Timer(start_time: float, kind: Kind | NAType)

A timer for measuring the time between two events.

ATTRIBUTE DESCRIPTION
start_time

The time at which the timer was started.

TYPE: float

kind

The method of timing.

TYPE: Kind | NAType

Interval dataclass #

Interval(
    start: float,
    end: float,
    kind: Kind | NAType,
    unit: Unit | NAType,
)

A time interval.

ATTRIBUTE DESCRIPTION
start

The start time.

TYPE: float

end

The end time.

TYPE: float

kind

The type of timer used.

TYPE: Kind | NAType

unit

The unit of time.

TYPE: Unit | NAType

duration property #
duration: float

The duration of the time interval.

to_dict #
to_dict(*, prefix: str = '') -> dict[str, Any]

Convert the time interval to a dictionary.

Source code in src/amltk/profiling/timing.py
def to_dict(self, *, prefix: str = "") -> dict[str, Any]:
    """Convert the time interval to a dictionary."""
    return {
        f"{prefix}start": self.start,
        f"{prefix}end": self.end,
        f"{prefix}duration": self.duration,
        f"{prefix}kind": self.kind,
        f"{prefix}unit": self.unit,
    }

Kind #

Bases: str, Enum

An enum for the type of timer.

from_str classmethod #
from_str(key: Any) -> Kind | NAType

Get the enum value from a string.

PARAMETER DESCRIPTION
key

The string to convert.

TYPE: Any

RETURNS DESCRIPTION
Kind | NAType

The enum value.

Source code in src/amltk/profiling/timing.py
@classmethod
def from_str(cls, key: Any) -> Timer.Kind | NAType:
    """Get the enum value from a string.

    Args:
        key: The string to convert.

    Returns:
        The enum value.
    """
    if isinstance(key, Timer.Kind):
        return key

    if isinstance(key, str):
        try:
            return Timer.Kind[key.upper()]
        except KeyError:
            return pd.NA

    return pd.NA

Unit #

Bases: str, Enum

An enum for the units of time.

from_str classmethod #
from_str(key: Any) -> Unit | NAType

Get the enum value from a string.

PARAMETER DESCRIPTION
key

The string to convert.

TYPE: Any

RETURNS DESCRIPTION
Unit | NAType

The enum value.

Source code in src/amltk/profiling/timing.py
@classmethod
def from_str(cls, key: Any) -> Timer.Unit | NAType:
    """Get the enum value from a string.

    Args:
        key: The string to convert.

    Returns:
        The enum value.
    """
    if isinstance(key, Timer.Unit):
        return key

    if isinstance(key, str):
        try:
            return Timer.Unit[key.upper()]
        except KeyError:
            return pd.NA

    return pd.NA

from_dict classmethod #

from_dict(d: Mapping[str, Any]) -> Interval

Create a time interval from a dictionary.

Source code in src/amltk/profiling/timing.py
@classmethod
def from_dict(cls, d: Mapping[str, Any]) -> Timer.Interval:
    """Create a time interval from a dictionary."""
    return Timer.Interval(
        start=dict_get_not_none(d, "start", np.nan),
        end=dict_get_not_none(d, "end", np.nan),
        kind=Timer.Kind.from_str(dict_get_not_none(d, "kind", pd.NA)),
        unit=Timer.Unit.from_str(dict_get_not_none(d, "unit", pd.NA)),
    )

na classmethod #

na() -> Interval

Create a time interval with all values set to None.

Source code in src/amltk/profiling/timing.py
@classmethod
def na(cls) -> Timer.Interval:
    """Create a time interval with all values set to `None`."""
    return Timer.Interval(
        start=np.nan,
        end=np.nan,
        kind=pd.NA,
        unit=pd.NA,
    )

start classmethod #

start(
    kind: Kind | Literal["cpu", "wall", "process"] = "wall"
) -> Timer

Start a timer.

PARAMETER DESCRIPTION
kind

The type of timer to use.

TYPE: Kind | Literal['cpu', 'wall', 'process'] DEFAULT: 'wall'

RETURNS DESCRIPTION
Timer

The timer.

Source code in src/amltk/profiling/timing.py
@classmethod
def start(
    cls,
    kind: Timer.Kind | Literal["cpu", "wall", "process"] = "wall",
) -> Timer:
    """Start a timer.

    Args:
        kind: The type of timer to use.

    Returns:
        The timer.
    """
    if kind in (Timer.Kind.WALL, "wall"):
        return Timer(time.time(), Timer.Kind.WALL)

    if kind in (Timer.Kind.CPU, "cpu"):
        return Timer(time.perf_counter(), Timer.Kind.CPU)

    if kind in (Timer.Kind.PROCESS, "process"):
        return Timer(time.process_time(), Timer.Kind.PROCESS)

    raise ValueError(f"Unknown timer type: {kind}")

stop #

stop() -> Interval

Stop the timer.

RETURNS DESCRIPTION
Interval

A tuple of the start time, end time, and duration.

Source code in src/amltk/profiling/timing.py
def stop(self) -> Interval:
    """Stop the timer.

    Returns:
        A tuple of the start time, end time, and duration.
    """
    if self.kind == Timer.Kind.WALL:
        end = time.time()
        return Timer.Interval(
            self.start_time,
            end,
            Timer.Kind.WALL,
            Timer.Unit.SECONDS,
        )

    if self.kind == Timer.Kind.CPU:
        end = time.perf_counter()
        return Timer.Interval(
            self.start_time,
            end,
            Timer.Kind.CPU,
            Timer.Unit.SECONDS,
        )

    if self.kind == Timer.Kind.PROCESS:
        end = time.process_time()
        return Timer.Interval(
            self.start_time,
            end,
            Timer.Kind.PROCESS,
            Timer.Unit.SECONDS,
        )

    raise ValueError(f"Unknown timer type: {self.kind}")

time classmethod #

time(
    kind: Kind | Literal["cpu", "wall", "process"] = "wall"
) -> Iterator[Interval]

Time a block of code.

PARAMETER DESCRIPTION
kind

The type of timer to use.

TYPE: Kind | Literal['cpu', 'wall', 'process'] DEFAULT: 'wall'

YIELDS DESCRIPTION
Interval

The Time Interval. The start and end times will not be

Interval

valid until the context manager is exited.

Source code in src/amltk/profiling/timing.py
@classmethod
@contextmanager
def time(
    cls,
    kind: Timer.Kind | Literal["cpu", "wall", "process"] = "wall",
) -> Iterator[Interval]:
    """Time a block of code.

    Args:
        kind: The type of timer to use.

    Yields:
        The Time Interval. The start and end times will not be
        valid until the context manager is exited.
    """
    timer = cls.start(kind=kind)

    interval = Timer.na()
    interval.kind = timer.kind
    interval.unit = Timer.Unit.SECONDS

    try:
        yield interval
    finally:
        _interval = timer.stop()
        interval.start = _interval.start
        interval.end = _interval.end