Weird timing issue with Thread.sleep

Marco Leise Marco.Leise at gmx.de
Sun Aug 14 18:03:19 PDT 2011


Am 03.08.2011, 19:21 Uhr, schrieb Steven Schveighoffer  
<schveiguy at yahoo.com>:

> On Wed, 03 Aug 2011 13:14:50 -0400, Andrej Mitrovic  
> <andrej.mitrovich at gmail.com> wrote:
>
>> Take a look at this:
>>
>> import std.stdio;
>> import core.thread;
>>
>> void main()
>> {
>>     foreach (x; 0 .. 1000)
>>     {
>>         Thread.sleep(dur!("usecs")(999));
>>         writeln(x);
>>     }
>>
>>     foreach (x; 0 .. 1000)
>>     {
>>         Thread.sleep(dur!("usecs")(1000));
>>         writeln(x);
>>     }
>> }
>>
>> Compile and run it. The first foreach loop ends in an instant, while
>> the second one takes much much longer to finish, which is puzzling
>> since I've only increased the sleep while for a single microsecond.
>> What's going on?
>
> I can only imagine that the cause is the implementation is using an OS  
> function that only supports millisecond sleep resolution.  So  
> essentially it's like sleeping for 0 or 1 millisecond.  However, without  
> knowing your OS, it's hard to say what's going on.  On my linux install,  
> the timing seems equivalent.
>
> -Steve

I would have guessed it comes down to time shares. If the scheduler works  
at a rate of 1000Hz, you get 1ms delays, if it works at 250Hz you get 4ms.  
Going down to an arbitrarily small sleep interval may be unfeasible. It's  
just an idea, I haven't actually looked that up.


More information about the Digitalmars-d-learn mailing list