Welcome to et-stopwatch’s documentation!¶
et-stopwatch¶
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
sleep(1)
stopwatch.stop()
print(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):
sleep(1)
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.013295 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.
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():
print("hi")
sleep(2)
say_hi_and_sleep_two_seconds()
hi
say_hi_and_sleep_two_seconds : 2.003 s
Free software: MIT license
Documentation: https://et-stopwatch.readthedocs.io.
API¶
Module et_stopwatch¶
A class for timing a piece of code.
Inspiration taken from Python Timer Functions: Three Ways to Monitor Your Code
- class et_stopwatch.Stopwatch(message='Stopwatch', ndigits=6, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>, stats=False)[source]¶
Class for timing code fragments.
Constructor parameters:
- Parameters
message (str) – this text will appear when the Stopwatch object is printed
ndigits (int) – number of digits in returned or printed timings.
- start(message=None)[source]¶
Start or restart this
Stopwatch
object.- Parameters
message (str) – modify the message used when the Stopwatch object is printed.
- stop(stats=True)[source]¶
Stop the stopwatch.
- Parameters
stats (bool) – if False no statistics are acummulated.
- Returns
the number of seconds (float) since the most recent call to stop or start.
Note
Stop()
callsstart()
immediately before returning. This is practical in an iteration, but as such includes the overhead of the iteration. Callstart()
explicitly to avoid this as in:with Stopwatch(message='This took') as sw: for i in range(3): sw.start() # restart the stopwatch sleep(1) # only this is timed print(i, sw.stop(), 's') # stop the stopwatch and returns second since start
- property time¶
The number of seconds as measured in the most recent call to
stop()
.