Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

nlinux/timer-context-manager

Open more actions menu
 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
9 Commits
 
 
 
 

Repository files navigation

A timer as a context manager

When one wants to measure the wall clock time of a code snippet, one usually do:

start = time.time()
# ...
# Some code we want to time
# ...
end = time.time()
elapsed = start - end # in secs
elapsed_ms = elapsed * 1000 # in ms

I find this quite heavy to read and un-pythonic. timer allows you to do the exact same thing with a context manager:

with Timer() as t:
    # Some code we want to time
print t.elapsed_s
print t.elapsed_ms

The timer.Timer class

timer.Timer is a context manager with 5 attributes:

  • default_timer: a platform specific timer function (time.time for Unix platforms and time.clock for Windows platforms)
  • start: the time of the beginning of the execution of the code block, measured with default_timer
  • end: the time of the end of the execution of the code block, measured with default_timer
  • elapsed_s: the wall clock timing of the execution of the code block, in seconds
  • elapsed_ms: the wall clock timing of the execution of the code block, in miliseconds

Example

>>> from timer import Timer
>>> with Timer() as t:
... for i in xrange(10000000):
... pass
...
>>> print(t.start)
1341568310.06
>>> print(t.end)
1341568310.14
>>> print(t.elapsed_ms)
73.6618041992 # in miliseconds
>>> print(t.elapsed_s)
0.0736618041992 # in seconds

About

Time your code using a context manager

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 100.0%
Morty Proxy This is a proxified and sanitized view of the page, visit original site.