[erlang-questions] Minimum time for timer:sleep()?

Bob Ippolito bob@REDACTED
Mon Mar 19 00:08:27 CET 2007


On 3/18/07, James Hague <james.hague@REDACTED> wrote:
> Here's some simple code to test timer:sleep/1:
>
> test(Milliseconds) ->
>    T1 = now(),
>    timer:sleep(Milliseconds),
>    T2 = now(),
>    io:fwrite("elapsed: ~w\n", [timer:now_diff(T2, T1)]).
>
> On the recent model MacBook I tested this on, test(5) prints "elapsed:
> 10182".  In fact, any value less than 10 milliseconds sleeps for ~10
> milliseconds.  Considering that a message send/receive pair is
> measured in single-digit MICROseconds on the same machine, this is
> curious to me.   Does anyone have any insight into this behavior?
>
> (FWIW, timer:sleep/1 is implemented as a single receive statement.)

I have no idea what the Erlang VM does but I'd guess that this 10 msec
granularity comes from the fact that multiplexing syscalls like
select/poll or kqueue (at least on OS X) are about that accurate when
you use them to sleep.

If you wanted something more accurate you'd have to use a whole
pthread and nanosleep or polling.. neither of those are terribly easy
to pull off. You might get slightly different results depending on if
you're using smp or async threads... but I don't know what the
internals of the VM look like.

-bob



More information about the erlang-questions mailing list