Grigory
Grigory

Reputation: 31

High resolution timer in erlang


Does anybody know if it is possible to make a high resolution timer in Erlang?
According to documentation all timers and timeouts are measured in milliseconds.
There is need to make a delay in microseconds. For example, instead of
timer:apply_after(MilliSec, Module, Function, Arguments).
something like
timer:apply_after(MicroSec, Module, Function, Arguments).

Upvotes: 3

Views: 2210

Answers (2)

algking
algking

Reputation: 387

  1. In practice,if you need a timer,you should use eralng:send_after/3 or erlang:start_timer/3,instead of timer module. The Timer module use the timer process to implement the timer, if the application has too much timer ,it will block the timer process which will slow you application .
  2. erlang:send_after/3 and erlang:start_timer/3 has one difference.
    • erlang:start_timer/3 will send the message {timeout, TimerRef, Msg} to Dest after Time milliseconds. erlang:send_after/3 will send just the Msg to Dest after Time millisecond.
    • The problem is when you need to cancel the timer , and the Msg has been send,if you use erlang:send_after/3,it may cause logic handle issue.

Upvotes: -1

Paul Guyot
Paul Guyot

Reputation: 6347

Indeed, all timers and timeouts primitives are in milliseconds including :

Two methods could be considered to achieve a sub-millisecond timer:

  • use Erlang primitives to wait the truncated number of milliseconds and then adjust with a busy loop. Please note that erlang:now() is not a real time function as it is guaranteed to be monotonous (and this is quite expensive). You should use os:timestamp() instead;
  • write native code that spawns a thread that will send a message when the timer fires. This could easily be implemented as a NIF.

Upvotes: 3

Related Questions