[erlang-questions] I'm having a SNAFU moment: timer:sleep/1
Roberto Ostinelli
roberto@REDACTED
Mon Jan 12 11:46:40 CET 2015
Additionally:
6> test:sleep_periodical(1000, 1).
Finished in 1999097 microsecond
So:
- Looping 1,000 times and sleeping 1 ms each time takes 2.00 seconds
(instead of 1).
Looks like it's ms related, not total count.
Best,
r.
On Mon, Jan 12, 2015 at 11:40 AM, Roberto Ostinelli <roberto@REDACTED>
wrote:
> 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:
>
> -module(test).
> -export([sleep_periodical/2]).
> -export([sleep_loop/2]).
>
> 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).
> {ok,test}
> 2> test:sleep_periodical(1000, 10).
> Finished in 12257397 microseconds.
> ok
> 3> test:sleep_periodical(2000, 10).
> Finished in 24518070 microseconds.
> ok
> 4> test:sleep_periodical(10000, 1).
> Finished in 20000280 microseconds.
> ok
> 5> test:sleep_periodical(20000, 1).
> Finished in 40000685 microseconds.
> ok
>
> So:
>
> - 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! ^^_
> r.
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150112/e79f0c53/attachment.htm>
More information about the erlang-questions
mailing list