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

Samuel Rivas samuelrivas@REDACTED
Tue Mar 20 08:32:22 CET 2007


James Hague wrote:
> Thanks everyone for the replies, though I still haven't worked out a
> solution I'm happy with.  Here's the details of what I'm trying to do:
> 
> I have an Erlang program that communicates with an external graphics
> "driver" program.  This way I can put pretty pictures on the screen
> but without having to micromanage everything from Erlang itself.  What
> I was attempting to do was to get updates running more or less at 60
> Hz (16 microseconds per frame).
> 
> My first idea was to track execution time per frame, then sleep the
> rest of the 16 millisecond slice.  This didn't work because sleep
> waits a minimum of 10 milliseconds, regardless of the value passed in.
> 
> My second idea was to spawn a process at the start of a frame, wait 16
> milliseconds in that process, then send a message to the original
> process,  This works, except the 16 millisecond time can vary quite a
> bit: from 16.8 ms to 22+ ms in my tests.

  Since sleeps are inaccurate, you may have to work out how much to
sleep before doing it. Also, you must keep a reference to the "origin"
to avoid drifting because of uneven waits.

  Regards.
-- 
	Samuel
-------------- next part --------------
-module(sleep).

-export([tic/1]).

tic(Ms) ->
    tic(Ms, now(), 0).

tic(Ms, Then, N) ->
    Now = now(),
    sleep_until(N*Ms, Then, Now),
    io:format("~p~n", [Now]),
    tic(Ms, Then, N + 1).

sleep_until(Ms, Then, Now) ->
    case timer:now_diff(Now, Then) of
	N when N < Ms * 1000 ->
	    timer:sleep(Ms - N div 1000);
	_ ->
	    true
    end.


More information about the erlang-questions mailing list