File size: 1,744 Bytes
13aa528
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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}")