MicroTimer - A Timer module with microsecond resolution

Hello,
I’ve just released MicroTimer a Timer module with microsecond resolution.

It allows you to sleep for as low as it takes to the Beam to send a message (usually around 3-5 μs).

It also contains function to send messages or run functions after a timeout or repeatedly every timeout μs.

Beware that the system sleep does nothing when it’s waiting and consumes no CPU, while this functions may waste CPU cycles for a maximum of 2ms every call.

It’s usually not a big deal, but it’s better to consider it.

The main reason this library was born is to sync with uneven frequencies that cannot be expressed in integer milliseconds.

One example is game loops that run at 60 FPS (it’s 16.667ms or 16,667μs every frame), if you use plain integers you have to use 16ms, which is 62.5FPS, or you have to use different timeouts (for example 56 frames of 17ms + 4 of 16ms) that could make the experience annoying, depending on the type of game.

The system sleep is also a lot less precise: in my measurements the system function had a std deviation of around 2,200μs (2.2ms), while MicroTimer.sleep std deviation was 16μs (0.016ms) for the same dataset.

Check out the bench folder to see how the times were taken or run your own tests.

7 Likes

great stuff! Reminded me of my childhood experiments with a more precise sleep.
Did a small benchmark that runs on Github: GitHub - d-led/various-benchmarks-erlang
various-benchmarks-erlang/test/bench_microtimer_send_after.erl at main · d-led/various-benchmarks-erlang · GitHub