MicroTimer
A timer module with microsend resolution.
MicroTimer can sleep for as low as it takes to the BEAM to send a message
(usually 3-5µ).
It can also send messages and invoke functions after a timeout or repeatedly
every timeout µs.
Keep in mind that the system sleep primitive literally waits doing nothing, consuming no CPU whatsoever, while µsleep is implemented with message passing
and wastes CPU cycles for a maximum of 2ms per call.
The CPU load shouldn't be a problem anyway, but it's definitely non-zero.
Installation
The package can be installed by adding micro_timer to your list of dependencies in mix.exs:
def deps do
[
{:micro_timer, "~> 0.1.0"}
]
endAPI
MicroTimer has a very simple API
usleep(timeout)and the aliasµsleep(timeout)
sleep fortimeoutµs.apply_after(timeout, executable, args \\ [])
invoke theexecutableaftertimeoutµs with the argsargsexecutablecan be the tuple{Module, :function}or a functionapply_every(timeout, executable, args \\ [])
invoke theexecutableeverytimeoutµs with the argsargssend_after(timeout, message, pid \\ self())
sendmessageaftertimeoutµs topid
ifpidis empty, the message is sento toself()send_every(timeout, message, pid \\ self())
sendmessageeverytimeoutµs topidcancel_timer(timer)
cancel thetimercreated by one ofapply_after,apply_every,send_afterandsend_every
*_after and *_avery return a timer reference that is just a regular pid.
You can check if the timer is still active or not with a simple call to Process.alive?(pid)
Basic Usage
iex(1)> :timer.tc(fn -> MicroTimer.usleep(250) end)
{257, :ok}
iex(2)> MicroTimer.send_after(666, :msg)
#PID<0.222.0>
# approximately 666µs later
iex(3)> flush
:msg
:ok
Check out the examples folder in this repository for more realistic examples.
Full documentation can be found at https://hexdocs.pm/micro_timer.
Benchmarks
License
MicroTimer is released under the MIT License - see the LICENSE file.