A Stopwatch for timing blocks of code
Project description
Python Stopwatch
This module contains a class and a function to time your code easily
Below are some examples:
First import the Stopwatch class
from stopwatch import Stopwatch
For the purpose of the tutorial were going to use this function which takes about 1.5 seconds to run
def func():
x = ''
for i in range(1_000_000):
x += str(i)
Using the with statement:
with Stopwatch() as sw:
func()
print(sw.time_elapsed)
1.4438485999708064
Or you can print the instance itself, which will return a nicely formatted string:
print(sw)
Time elapsed: 1.444
You can also a pass an instance of a class to automatically add the time taken to the total elapsed time of the insatnce:
sw = Stopwatch()
with sw:
func()
func()
with sw:
func()
print(sw)
'2.7854167000041343'
The above example is the equivalent of:
sw = Stopwatch()
sw.start()
func()
sw.stop()
func()
sw.start()
func()
sw.stop()
print(sw)
'2.9421735999640077'
You can also use the decorator to time a function every time you run it
First import the decorator:
from stopwatch import time_it
Add it to your function:
@time_it()
def func():
x = ''
for i in range(1_000_000):
x += str(i)
Now it will return a tuple with the time taken and the output of the function (which in our case is None)
print(func())
(1.1367347000050358, None)
You can also add the time taken to an existing instance of Stopwatch like so:
sw = Stopwatch()
@time_it(stopwatch=sw)
def func():
x = ''
for i in range(1_000_000):
x += str(i)
Call the function twice:
print('Out:', func())
print('Total time elapsed:', sw.time_elapsed)
print('Out:', func())
print('Total time elapsed:', sw.time_elapsed)
Out: (1.3642582000466064, None)
Total time elapsed: 1.3642542000161484
Out: (1.3336866000317968, None)
Total time elapsed: 2.6979382000281475
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for ez_stopwatch-1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1cb3f2015480070b04b9128f02cbf4190a1ad6060b008cffe4c6d517affa97c4 |
|
MD5 | 716fb981fb5e35c867dddcd49adb244b |
|
BLAKE2b-256 | 709a8671add6e54301c44e74ef17d912402e3b2262377d7165babc9fce4415f7 |