[ANN] Timers.jl tic() toc() and accurate delays

The package GitHub - ufechner7/Timers.jl: Timers for Julia provides the helper functions tic() and `toc() that where removed from Julia in version 1.0.

I still find them very useful, for example to measure the time until a program is loaded.

In addition it provides the function:

delay_ms(time_ms)

with an accuracy of better than 100 nanoseconds ±0.2%, but only if the system is not fully loaded.

This is is much better than the accuracy of the function sleep() which has - for me - an error of
16ms (!) on Windows and of 1 to 2 ms on Linux.

Finally it provides the function

wait_until(finish_ns; always_sleep=false)

that sleeps until the given time [ns] is reached. Example:

dt = 0.05
start = time_ns()
for i in 1:100
    # do some work
    wait_until(start + i*dt*1e9)
end

The section “# do some work” is executed exactly every 50ms as long as executing this section takes less than 50ms.

The additional parameter always_sleep can be set to true if you want to ensure that the sleep function
is always called for at least 1 ms. This is useful if you need to ensure that cooperative multitasking
works even for the price to miss the deadline.

To test the accuracy on your machine, you can run:

using Pkg
pkg"test Timers"

If you want more Timers, please create an issue for the package on Github.

The accuracy seems to be much better.
sleep seems to be 1 ms off by default.

7-element BenchmarkTools.BenchmarkGroup:
  tags: ["sleep_ms"]
  "100µs" => TrialEstimate(100.068 μs)
  "200µs" => TrialEstimate(200.068 μs)
  "5ms" => TrialEstimate(5.000 ms)
  "1ms" => TrialEstimate(1.000 ms)
  "10ms" => TrialEstimate(10.000 ms)
  "500µs" => TrialEstimate(500.067 μs)
  "2ms" => TrialEstimate(2.000 ms)
5-element BenchmarkTools.BenchmarkGroup:
  tags: ["sleep"]
  "20ms" => TrialEstimate(21.239 ms)
  "5ms" => TrialEstimate(6.299 ms)
  "1ms" => TrialEstimate(2.054 ms)
  "10ms" => TrialEstimate(11.306 ms)
  "2ms" => TrialEstimate(3.252 ms)

Good job!

TickTock.jl says “Hi!” :slight_smile:

Thank you! Yes, a little bit of overlap with your package, but I want to implement more the functionality of the Timer class of QT to be used more by programs and not so much on the command line. I will also add Observables to bind functions to timer events.