# Sub-millisecond Timer Precision

**URL:** <https://forum.elixirforum.com/t/sub-millisecond-timer-precision/19618>\
**Category:** Questions\
**Tags:** nif, timer, dirty-scheduler\
**Created:** [January 23, 2019, 12:49pm UTC](https://forum.elixirforum.com/t/sub-millisecond-timer-precision/19618 "2019-01-23T12:49:18Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![massimo](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/massimo/32/5555_2.png) [@massimo](https://forum.elixirforum.com/u/massimo)\
**Post date:** [January 24, 2019, 1:25pm UTC](https://forum.elixirforum.com/t/sub-millisecond-timer-precision/19618/8 "2019-01-24T13:25:41Z")

</div>

shameless plug

I wrote a library with the same api of `:timer` but with a resolution in microseconds

it’s called [micro\_timer](https://hex.pm/packages/micro_timer)

> [@devonestes](#):
>
> I believe the 1ms resolution is the lowest common (reliable) denominator of all the platforms the BEAM runs on. It’s possible to go use a much smaller resolution on most platforms, but not all of them, unfortunately.

I did some investigations before writing my own module and I think the relevant snippet of the Erlang sleep implementation is this one

```
    int
erts_milli_sleep(long ms)
{
    if (ms > 0) {
#ifdef __WIN32__
  Sleep((DWORD) ms);
#else
  struct timeval tv;
  tv.tv_sec = ms / 1000;
  tv.tv_usec = (ms % 1000) * 1000;
  if (select(0, NULL, NULL, NULL, &tv) < 0)
      return errno == EINTR ? 1 : -1;
#endif
    }
    return 0;
}

```

`Sleep` for win32 is defined as

```
void Sleep(
  DWORD dwMilliseconds
);

```

It only accepts milliseconds

There is a [win32 implementation of the `select` function](https://docs.microsoft.com/en-us/windows/desktop/api/winsock2/nf-winsock2-select) that take microseconds, but it’s in `Winsock2` API that are supported only from Windows Vista onward.

One could try to compile ERTS using a sleep function that supports microseconds, but I guess it would break a lot of existing software.

It should also be simple enough to write a NIF that supports sleeping for microseconds, once you have the sleep function, you can build all the other functionalities around it (it’s exactly what I did in my library, except the NIF part).

EDIT:  
for clarity" `sleep` in Erlang is implemented using the timeout for `receive`

```
-spec sleep(Time) -> 'ok' when
      Time :: timeout().
sleep(T) ->
    receive
    after T -> ok
end.

```

the snippet I was referring to is what I believe is the low level C implementation.

---

_[View the full topic](https://forum.elixirforum.com/t/sub-millisecond-timer-precision/19618)._
