wise-water's picture
init commit
13aa528
import logging
import time
def msec2human(ms) -> str:
"""
Converts milliseconds to a human-readable string representation.
Args:
ms (int): The input number of milliseconds.
Returns:
str: The formatted string representing the milliseconds in a human-readable format.
"""
s = ms // 1000 # Calculate the number of seconds
m = s // 60 # Calculate the number of minutes
h = m // 60 # Calculate the number of hours
m %= 60 # Get the remaining minutes after calculating hours
s %= 60 # Get the remaining seconds after calculating minutes
ms %= 1000 # Get the remaining milliseconds after calculating seconds
if h:
return (
f"{h} hour {m:2d} min" # Return the formatted string with hours and minutes
)
if m:
return f"{m} min {s:2d} sec" # Return the formatted string with minutes and seconds
if s:
return f"{s} sec {ms:3d} msec" # Return the formatted string with seconds and milliseconds
return f"{ms} msec" # Return the formatted string with milliseconds
class ElapsedTimer:
def __init__(self, name, logger=None, unit="ms"):
self.name = name
self.logger = logger or logging.getLogger(__name__)
def __enter__(self):
self.start_time = time.perf_counter()
self.logger.info(f"<{self.name}>: start")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
elapsed_time = time.perf_counter() - self.start_time
elapsed_time = msec2human(int(elapsed_time * 1000))
if exc_type:
self.logger.warning(f"<{self.name}> raised {exc_type}, {elapsed_time}")
else:
self.logger.info(f"<{self.name}>: {elapsed_time}")