[erlang-questions] I'm having a SNAFU moment: timer:sleep/1

Roberto Ostinelli roberto@REDACTED
Mon Jan 12 11:40:04 CET 2015

Dear list,
I've probably missed out something since I'm not understanding what is
going here.

I'm basically just trying to send messages periodically, though I found out
that I wasn't seeing the behavior that I was expecting. It looks like the
timer has some erratic behavior.

I've stripped out the code to the bare minimum and it looks like this:


sleep_periodical(Num, IntervalMs) ->
{Time, _Value} = timer:tc(?MODULE, sleep_loop, [Num, IntervalMs]),
io:format("Finished in ~p microseconds.~n", [Time]).

sleep_loop(Num, IntervalMs) ->
SleepFun = fun(_) -> timer:sleep(IntervalMs) end,
lists:foreach(SleepFun, lists:seq(1, Num)).

When I run this code, I see the following:

Erlang/OTP 17 [erts-6.3] [source] [64-bit] [smp:8:8] [async-threads:10]
[hipe] [kernel-poll:false] [dtrace]

Eshell V6.3  (abort with ^G)
1> c(test).
2> test:sleep_periodical(1000, 10).
Finished in 12257397 microseconds.
3> test:sleep_periodical(2000, 10).
Finished in 24518070 microseconds.
4> test:sleep_periodical(10000, 1).
Finished in 20000280 microseconds.
5> test:sleep_periodical(20000, 1).
Finished in 40000685 microseconds.


   - Looping 1,000 times and sleeping 10 ms each time takes 12.26 seconds
   (instead of 10).
   - Looping 2,000 times and sleeping 10 ms each time takes 24.52 seconds
   (instead of 20).
   - Looping 10,000 times and sleeping 1 ms each time takes 20.00 seconds
   (instead of 10).
   - Looping 20,000 times and sleeping 1 ms each time takes 40.00 seconds
   (instead of 20).

Up to 10,000 times it takes 12,16% (1/8) more time, from 10,000 times it
takes 100% (double).

Can some kind soul explain what I'm doing wrong here and how to achieve the
desired results?

I'm on OSX, Erlang 17.4.

Help! ^^_
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150112/9af124bd/attachment.htm>

More information about the erlang-questions mailing list