time.sleep accuracy

David Bolen db3l at fitlinxx.com
Tue Sep 19 06:08:11 CEST 2000

Peter Hansen <peter at engcorp.com> writes:

> Is the latter statement more than just theory?  I strongly doubt that
> Windows, for example, would consistently come in any closer than +/- ten
> or twenty milliseconds.  Maybe on a real-time operating system.

Well, it's definitely OS-dependent, since the implementation of
time.sleep() is different by OS.  Under Windows, it's using select(),
so it depends on the native select() implementation's resolution, and
obviously the resolution of the system scheduler in waking up a task
that is ready to run.  But at least under WinNT, it seems to be
awfully good - at least better than I would have expected.

> I have not had opportunity to test either way...

Different parts of the time module have different resolutions, and as
it turns out although I'm not sure if the select() granularity is
documented, you can run some rough tests...

The time.time() uses C library functions to establish the time, and
could have fairly limited resolution - from some brief tests under
WinNT 4.0 for example I get about a 10ms resolution on time.time(),
but presumably that may also differ by platform.

But time.clock() is designed to return the highest resolution of the
platform, and on that same WinNT system it uses the performance
counter, which for me yields resolution just under 1uS.  In practice,
a tight while 1: print time.clock() was running fast enough to show
sub-ms resolution.

So if you use time.clock() to clock how long a time.sleep() takes, you
can get a rough feeling as to how accurate it is, and again on that
same WinNT system it seemed fairly good - I seemed to be getting a
recording of about .3-.4ms for something like

	time.clock(); time.sleep(x); time.clock()

which presumably has some overhead for parsing the actual call to
sleep and the second call to clock.

Of course, there probably needs to be a huge caveat here that I've
seen the Windows scheduler really get bogged down at times so if
you're doing other stuff on the machine, I'm sure that although the
basic precision is there, it's entirely possible to get a horrible
worst case, and the only real guarantees would be to run at the real
time priority which can really mess things up if you do something
wrong :-)

-- David
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \

More information about the Python-list mailing list