As a followup to my last blog post on timings, I present the following function which works as both a decorator and a context manager.
# timethis.py import time from contextlib import contextmanager def timethis(what): @contextmanager def benchmark(): start = time.time() yield end = time.time() print("%s : %0.3f seconds" % (what, end-start)) if hasattr(what,"__call__"): def timed(*args,**kwargs): with benchmark(): return what(*args,**kwargs) return timed else: return benchmark()
Here is a short demonstration of how it works:
# Usage as a context manager with timethis("iterate by lines (UTF-8)"): for line in open("biglog.txt",encoding='utf-8'): pass # Usage as a decorator @timethis def iterate_by_lines_latin_1(): for line in open("biglog.txt",encoding='latin-1'): pass iterate_by_lines_latin_1()
If you run it, you'll get output like this:
bash % python3 timethis.py iterate by lines (UTF-8) : 3.762 seconds <function iterate_by_lines_latin_1 at 0x100537958> : 3.513 seconds
Naturally, this bit of code would be a good thing to bring into your next code review just to make sure people are actually paying attention.
Subscribe to Posts [Atom]