[erlang-questions] Sending message at a specific and accurate time

Joe Armstrong <>
Sun Feb 21 22:20:33 CET 2016


I tried a simpler program:

test() -> test(10, []).

test(0, L) ->
    L;
test(K, L) ->
    T1 = ms_time(),
    erlang:send_after(5000, self(), ping),
    receive
      ping ->
         T2 = ms_time(),
          test(K-1, [T2-T1|L])
    end.

ms_time() ->
    erlang:system_time() div 1000000.

Running this gives the following times

[5001,5001,5006,5006,5002,5003,5006,5002,5002,5006]

I'd expected 5000 or 5001

This is in an unloaded OS with an unloaded erlang. 6ms seems very long -
there are very few processes running and the system load is virtually zero.

I tried erl -snp disable and setting process_flag(priority, max) but the results
are pretty much the same.

Waiting for shorter times like 100 ms makes no difference - still
events with a 6 ms delay.

I want to use this for scheduling music events (controlling synths) and these
delays are far more than I expected.

/Joe



On Sun, Feb 21, 2016 at 8:32 PM, Jesper Louis Andersen
<> wrote:
>
> On Sun, Feb 21, 2016 at 7:53 PM, Joe Armstrong <> wrote:
>>
>> I'm getting about a 4 - 9 ms. inaccuracy in the time the messages is sent
>> and
>> the time I want it to be sent - but I'd like it to be much more accurate
>> (sub ms if possible)
>
>
> I would start by making measurements without the network component. When you
> would send the gen_udp message, you take a timestamp, and analyze the skew
> from the suggested skew. This lets you estimate the overhead of the rest of
> the system in isolation from your own code and the Erlang VM.
>
> Intuitively, 4 to 9 milliseconds is much higher than what I would expect.
> But note that if you sleep for, say, 40ms, you will be awoken on the 41ms
> flank at the earliest. This is because you are usually "inside" a
> millisecond when you make the call so you start by taking the ceiling of
> that milli-second before you.
>
> How much other work is your Erlang VM doing when you make these
> measurements? You are saying between 4 to 9 ms, which is variance suggesting
> the VM has lots of work to do at that moment. And of course such stuff will
> affect the running time. You can switch priority of your processes up to
> high, but this comes at the expense of other calculations if you can't
> finish your work quickly in the process with high priority.
>
>
> --
> J.


More information about the erlang-questions mailing list