python-stopwatch2

website·Indexed 29 days ago

https://stopwatch2.vercel.app/

A Python library for timing and profiling code execution. It provides a Stopwatch class, support for the 'with' statement, and a @profile decorator for function profiling. The library includes tools for calculating statistics (mean, median, max, and deviation) and formatting elapsed time.

Tokens
2.8K
Snippets
20
Records
24
Agent score
75%

What's inside python-stopwatch2

  1. Use the Lap class to track individual lap timing

    The Lap class represents a single lap within a stopwatch session. It tracks whether the lap is currently active and the total time that has passed during that lap.
  2. Initialize and use the Stopwatch class

    The Stopwatch class is used to measure elapsed time. It can be used as a context manager to automatically stop the timer when the block exits. If print_report is set to True, the elapsed time is automatically printed upon exiting the with block.
    from stopwatch import Stopwatch
    from time import sleep
    
    # Basic usage with a name
    with Stopwatch('my stopwatch') as sw:
        sleep(3)
    print(sw.report())
    # Output: [Stopwatch#my stopwatch] total=3.00s
    
    # Auto-print report on exit
    with Stopwatch('my custom message', True):
        sleep(3)
    # Output: [__main__:<module>:1] ~ 3.00s - my custom message
    
    # Custom precision
    with Stopwatch(precision=3) as sw:
        sleep(3)
    print(str(sw))  # 3.000s
  3. Track time intervals using Stopwatch laps

    The lap() method is a context manager that creates a new lap within the current stopwatch session. All laps are stored in the laps attribute, and the statistics attribute provides aggregated data (min, max, mean) based on these laps.
    with Stopwatch() as sw:
        for i in range(5):
            with sw.lap(): 
                sleep(i / 10)
    
    print(len(sw.laps))  # 5
    print(sw.statistics.maximum)  # 0.4
    print(sw.statistics.mean)      # 0.2
  4. Install python-stopwatch2

    Install the python-stopwatch2 library using Poetry or pip depending on your operating system.
    # Using Poetry
    poetry add python-stopwatch2
    
    # Using pip (Linux/macOS)
    python3 -m pip install python-stopwatch2
    
    # Using pip (Windows)
    py -3 -m pip install python-stopwatch2
  5. Profile a function using the @profile decorator

    Use the @profile decorator from the stopwatch library to track the execution time of a function. The decorator prints a performance report (including hits, mean, min, median, max, and deviation) every time the function is called, and prints a final summary report after the program execution ends. You can optionally specify a custom name for the function in the report using the name parameter.
    from stopwatch import profile
    from time import sleep
    
    @profile(name='My function')
    def wait_for(time: float) -> None:
        sleep(time)
    
    for time in [0.1, 0.2, 0.3, 0.4, 0.5]:
        wait_for(time)
    print('end')
    
    # Example Output:
    # [__main__#My function] hits=1, mean=100.14ms, min=100.14ms, median=100.14ms, max=100.14ms, dev=0.00μs
    # ...
    # end
    # [__main__#My function] hits=5, mean=300.35ms, min=100.14ms, median=300.35ms, max=500.55ms, dev=141.56ms
  6. Measure execution time using Stopwatch as a context manager

    The Stopwatch class supports Python's with statement, allowing you to wrap a block of code to measure its elapsed time. When used as a context manager, the stopwatch instance is returned as the context variable, which can be printed to retrieve the total time elapsed.
    from stopwatch import Stopwatch
    from time import sleep
    
    with Stopwatch() as my_stopwatch:
        sleep(3)
    
    print(f'Time elapsed: {my_stopwatch}')  # Output: Time elapsed: 3.00s
  7. Stopwatch initialization parameters

    The Stopwatch constructor accepts the following parameters:

    • name (Optional[str]): The name of the stopwatch used for reporting.
    • print_report (bool): If True, prints the elapsed time at the end of a with statement. Defaults to False.
    • precision (int): The number of decimal places to use for time formatting. Defaults to 2.
    def __init__(
        self,
        name: Optional[str] = None,
        print_report: bool = False,
        precision: int = 2
    ) -> None:
  8. Manage Stopwatch state with start, stop, reset, and restart

    The Stopwatch class provides methods to manually control the timer state:

    • start(): Starts the stopwatch if it is not already running. This is called automatically upon creation.
    • stop(): Stops the stopwatch and freezes the duration. This is called automatically when exiting a with block.
    • reset(): Resets the duration to 0 and stops the stopwatch.
    • restart(): Resets the duration to 0 and starts the stopwatch immediately.
    sw = Stopwatch()
    sleep(2)
    sw.stop()
    print(sw.elapsed)  # 2.0
    
    sw.start()
    sleep(1)
    sw.stop()
    print(sw.elapsed)  # 3.0
    
    sw.reset()
    print(sw.elapsed)  # 0.0
  9. Generate a Stopwatch statistics report

    The report() method returns a formatted string containing the total elapsed time and statistical data (mean, minimum, median, maximum, and deviation) for all recorded laps.
    with Stopwatch() as sw:
        for i in range(5):
            with sw.lap():
                sleep(i / 10)
    print(sw.report())
    # Output: [Stopwatch] total=1.0s, mean=0.2s, min=0.0s, median=0.2s, max=0.4s, dev=0.1s
  10. Export all statistics to a dictionary

    The to_dict() method returns a dictionary containing all calculated statistics (mean, maximum, median, minimum, total, and variance) mapped to their respective float values.
    from stopwatch import Stopwatch
    from random import randint
    from time import sleep
    
    with Stopwatch() as sw:
        for _ in range(1, 6):
            with sw.lap():
                sleep(randint(1, 10) / 10)
    
    stats_dict = sw.statistics.to_dict()
    # Example output: {'mean': 0.5, 'maximum': 0.9, 'median': 0.5, 'minimum': 0.1, 'total': 2.5, 'variance': 0.09}
  11. Compare python-stopwatch2 with other Python timer libraries

    When choosing a timer library for Python, python-stopwatch2 provides a comprehensive feature set including unit tests, statistics, lap timing, static typing, documentation, and docstrings, whereas other libraries like stopwatch.py and python-stopwatch lack several of these capabilities.
    LibraryUnit testsStatisticsLapsStatic TypingDocsDocstring
    stopwatch.py✅❌❌❌❌❌
    python-stopwatch❌✅✅❌❌❌
    python-stopwatch2✅✅✅✅✅✅