Skip to main content

A class for timing code (start/stop, context manager, decorator).

Project description

A class for timing code. A Stopwatch object can be used to time code using its start and stop methods:

from et_stopwatch import Stopwatch

stopwatch = Stopwatch() # create and start the stopwatch

stopwatch : 1.003744 s

Use as a context manager:

with Stopwatch(message='This took') as sw: # using a custom message
    for i in range(3):
        print(i, sw.stop(), 's') # stop() returns the time since the last call to start|stop in seconds

0 1.004943
1 1.004948
2 1.003404
This took :
    total  : 3.0132949999999994 s
    minimum: 1.003404 s
    maximum: 1.004948 s
    mean   : 1.004432 s
    stddev : 0.000727 s
    count  : 3

Since stop was called more than once, some statistics are printed. Calling stop automatically restarts the stopwatch and as a consequence the stopwatch also measures the overhead of the iteration over i. To avoid this, explicitly call start:

with Stopwatch(message='This took') as sw:
    for i in range(3):
        sw.start()               # restart the stopwatch
        print(i, sw.stop(), 's') # stop() returns the time since the last call to start|stop in seconds

0 1.004388
1 1.004173
2 1.003048
This took :
    total  : 3.011609 s
    minimum: 1.003048 s
    maximum: 1.004388 s
    mean   : 1.00387 s
    stddev : 0.000588 s
    count  : 3

This time, the timing are slightly shorter for each iteration.

Use as a decorator:

@Stopwatch(name="say_hi_and_sleep_two_seconds", ndigits=3) # custom message, print only 3 digits.
def say_hi_and_sleep_two_seconds():


say_hi_and_sleep_two_seconds : 2.003 s

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

et-stopwatch-1.0.1.tar.gz (4.2 kB view hashes)

Uploaded source

Built Distribution

et_stopwatch-1.0.1-py3-none-any.whl (4.5 kB view hashes)

Uploaded py3

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page