time.sleep accuracy

Jake Baker jbaker at ummelec.com
Tue Sep 19 12:12:40 EDT 2000


>> Nick Collier <nick at src.uchicago.edu> wrote:
>> 
>> > I'm wondering if anyone knows how accurate time.sleep is? For example,
>> > if I want to sleep for 50 milliseconds (time.sleep(.05)), what's the
>> > actual margin or error? Is this os dependent?

For any particular machine, the average minimum sleep() delay can be found by excersizing the following snippet:

def report_min_sleep():
	total = 0
	for i in range(1000):
		c = time.clock()
		time.sleep(0.001)
		x = time.clock()
		total = total + x - c
	# print average delay in milliseconds
	print "%.2f" % total, " milliseconds"

(Note that the loop counter sentinel 1000 was carefully chosen - if you change it, you'll have to add some additional math to convert total to milliseconds)

Of course, that code is highly dependant on processor load etc, but I've always preferred heuristic measurements over idealized ones.

On a fairly old Win95 machine with moderate processor loads (lots of apps open, most of them idle) I get a result of 10.71 milliseconds. Several runs produced identical results, +- .01 milliseconds.

(The minimum and maximum sleep times for this test were 0.08 and 21.81 ms respectively.)

I ran a test where I replace time.sleep() in the above function with a call to:

def my_sleep(seconds):
	c = time.clock()
	while time.clock() - c < seconds:
		pass

(In other words, a busy wait.) Not unsurprisingly, the accuracy of this new sleep function was now 1.10 milliseconds, +- .01 millisecond.

So, if you are more interested in accuracy over a small period of time than actually suspending the process, it looks like a custom sleep() might be more appropriate. YMMV.






More information about the Python-list mailing list