Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Created September 20, 2020 11:26
Show Gist options
  • Save miraculixx/b90ecabb3c1697a8cdf3830efe2d0d88 to your computer and use it in GitHub Desktop.
Save miraculixx/b90ecabb3c1697a8cdf3830efe2d0d88 to your computer and use it in GitHub Desktop.
a straight forward statement timer for Python
@contextmanager
def timeit():
""" straight forward statement timer for Python
Usage:
with timeit() as timer:
...
print(timer.elpased()) # prints the timedelta, timer also has .start, .end
"""
from datetime import datetime as t
class timer: elapsed = None
tx = timer()
t0 = dt.now()
yield tx
t1 = dt.now()
tx.start = t0
tx.end = t1
tx.elapsed = t0 - t1
@miraculixx
Copy link
Author

miraculixx commented Sep 20, 2020

I just got tired of writing code like this:

t0 = datetime.datetime.now()
# do something to measure time for
...
# end  of something
t1 = datetime.datetime.now()
elapsed = t0 - t1

I'm sure someone else has already written that contextmanager, but couldn't be bothered with finding it :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment