views:

614

answers:

4

I am using the code below

Thread.Sleep(5);

at the end of a while loop. To try and get a 5ms delay between iterations.

Sometimes it sleeps for 16ms. This I understand and accept, since it depends on when the CPU gets around to servicing the thread. However once it has woken the next iteration it seems to wake immediately after the sleep call (I am logging with timestamps). Is there a problem with using such a short sleep interval that it is treated as zero?

+4  A: 

Most likely, the problem is simply that your timer has limited resolution. If it only updates, say, every 10ms, you're going to see the same timestamp on some iterations, even if 5ms have passed.

Which timer are you using to generate your timestamps?

jalf
+21  A: 

Your problem is like that on most modern machines, DateTime.UtcNow has a resolution of about 10-15ms (though I see the documentation says it's about 10ms since NT 3.5). If you want higher resolution timing, see the Stopwatch class, specifically Stopwatch.GetTimestamp().

Also note that Stopwatch will only use the high-resolution timers if they are available (Stopwatch.IsHighResolution will tell you at run-time). If not, it falls back to DateTime.UtcNow.Ticks.

Jonathan
A: 

What sort of system are you running this on? Small intervals can depend on the processor and how high a resolution it supports. I ran an app on a handheld once where the resolution of the timer itself was 16ms. So it may be hardware related. Try increasing the time period to say 30ms and see if it works then.

Ian
+1  A: 

If I remember correctly NT time slicing, which was introduced in the NT kernel and was still active in the same way as of XP, operates right around the 5ms mark. We were building a realtime application and ran in to that problem. You will not be able to consistently get a 5ms sleep time. What we found was that you will sometimes get 10 - 16 ms, sometimes no ms and occasionally yet rarely get 5 ms.

I was doing these tests around 5 years ago though so things may have changed since then.