[issue19495] Enhancement for timeit: measure time to run blocks of code using 'with'
Ezio Melotti
report at bugs.python.org
Fri Jun 20 05:41:49 CEST 2014
Ezio Melotti added the comment:
I often write code like:
import time
start = time.time()
...
end = time.time()
print(end - start)
Usually I don't do this to measure accurately the performance of some piece of code, but rather I do it for tasks that take some time (e.g. downloading a file, or anything that I can leave there for a while and come back later to see how long it took).
So I'm +1 on a simple context manager that replaces this common snippet, and -0 on something that tries to measure accurately some piece of code (if it takes a few seconds or more, high-accuracy doesn't matter; if it takes a fraction of seconds, I won't trust the result without repeating the measurement in a loop).
Regarding the implementation I can think about 2 things I might want:
1) a way to retrieve the time (possibly as a timedelta-like object [0]), e.g.:
with elapsed_time() as t:
...
print(t.seconds)
2) a way to print a default message (this could also be the default behavior, with a silent=True to suppress the output), e.g.:
>>> with elapsed_time(print=True):
... ...
...
Task terminated after X seconds.
For the location I think that the "time" module would be the first place where I would look (since I would have to otherwise import time() from there). I would probably also look at "timeit" (since I'm going to time something), even though admittedly it doesn't fit too much with the rest. While it might fit nicely in "contextlib", I won't probably expect to find it there unless I knew it was there in the first place.
[0] would making timedelta a context manager be too crazy?
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue19495>
_______________________________________
More information about the Python-bugs-list
mailing list