[erlang-questions] Unexpected behaviour of timer:sleep

Ulf Wiger (TN/EAB) ulf.wiger@REDACTED
Wed Mar 19 23:11:41 CET 2008

Scott Lystig Fritchie skrev:
> shehan <shehan@REDACTED> wrote:
> s> (test@REDACTED)15> timer:tc(timer, sleep, [1]).
> s> {15000,ok}
> s> I expected value is, between 1000 to 2000.
> Your expected value should be greater than or equal to the greater of:
>    1. the argument to timer:sleep/1
>    2. your OS's timer resolution
> A common value for #2 is 1/100th of a second for Linux kernels.

Just to be clear, this is also a result of running only
one activity within the Erlang node. If there is other
work going on, timeouts are handled more swiftly.

Consider the following:

Eshell V5.6  (abort with ^G)
1> [timer:tc(timer,sleep,[1]) || _ <- lists:duplicate(10,1)]. 
2> F = fun(Pid) -> spawn(fun() -> Pid ! 
{self(),timer:tc(timer,sleep,[1])} end) end.
3> [F(self()) || _ <- lists:duplicate(10,1)].
8> flush().
Shell got {<0.67.0>,{1810,ok}}
Shell got {<0.69.0>,{2316,ok}}
Shell got {<0.68.0>,{2360,ok}}
Shell got {<0.72.0>,{1733,ok}}
Shell got {<0.71.0>,{1773,ok}}
Shell got {<0.70.0>,{2355,ok}}
Shell got {<0.74.0>,{1072,ok}}
Shell got {<0.73.0>,{1679,ok}}
Shell got {<0.76.0>,{1505,ok}}
Shell got {<0.75.0>,{1553,ok}}

In the first case, all calls to sleep are serialized.
They all run pretty much undisturbed, and each take about
10 ms. In the second case, 10 calls to sleep are executed
in parallel (almost - only 1 CPU), and then take about
as long as one might expect.

If I do the same thing with 100 simultaneous processes, a
handful of timers will take about 15 ms, which is probably
due to scheduling delays.

Ulf W

More information about the erlang-questions mailing list