Skip to content

Instantly share code, notes, and snippets.

@glennzw
Created April 11, 2013 16:25
Show Gist options
  • Save glennzw/5364873 to your computer and use it in GitHub Desktop.
Save glennzw/5364873 to your computer and use it in GitHub Desktop.
Python monotonic clock
Sometimes you want a timer indepdent of the system clock, in case the system clock changes (e.g. ntpdate).
os.times() is the solution under Linux:
"Return a 5-tuple of floating point numbers indicating accumulated (processor or other) times, in seconds. The items are: user time, system time, children’s user time, children’s system time, and elapsed real time since a fixed point in the past, in that order. See the Unix manual page times(2) or the corresponding Windows Platform API documentation. On Windows, only the first two items are filled, the others are zero."
Under Windows, you could use time.clock(), which will return seconds since the process started. But on Linux the same function returns CPU usage.
Window One:
>>> import time
>>> import os
>>> start=int(os.times()[4])
>>> while True:
... print "%d seconds have elapsed" %( int(os.times()[4]) - start )
... time.sleep(1)
...
2 seconds have elapsed
3 seconds have elapsed
4 seconds have elapsed
5 seconds have elapsed
6 seconds have elapsed
7 seconds have elapsed
8 seconds have elapsed
Window Two:
date -s "2 OCT 2006 18:00:00"
date -s "2 OCT 2007 18:00:00"
date -s "2 OCT 1999 18:00:00"
(having no effect on our counter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment