Source code for nnsa.utils.code_performance

"""
This module contains functions dealing with assessing code performance.
"""

import time
from datetime import timedelta

import psutil

__all__ = [
    'Timer',
    'print_efficiency',
]


[docs]class Timer(object): """ Implements a context-manager timer. Args: ndecimals (int): number of decimals to print (for the seconds). By default rounds to 0 decimals, i.e., whole seconds. Examples: >>> with Timer(): # doctest: +SKIP ... s = [x**2 for x in range(10000000)] Elapsed time: 0:00:02.172509 """ def __init__(self, prefix="", ndecimals=None): self.ndecimals = ndecimals self.prefix = prefix def __enter__(self): self.start = time.time() def __exit__(self, type, value, traceback): self.end = time.time() dt = self.end - self.start if self.ndecimals is not None: dt = round(dt, self.ndecimals) print("{}\n\tElapsed time: {}".format(self.prefix, timedelta(seconds=dt)))