What is the best way in C++11 to implement a high-resolution timer that continuously checks for time in a loop, and executes some code after it passes a certain point in time? e.g. check what time it is in a loop from 9am onwards and execute some code exactly at 11am. I require the timing to be precise (i.e. no more than 1 microsecond after 9am).
I will be implementing this program on Linux CentOS 7.3, and have no issues with dedicating CPU resources to execute this task.
3
Answers
Instead of implementing this manually, you could use e.g. a
systemd.timer
. Make sure to specify the desired accuracy which can apparently be as precise as 1us.My suggestion would be to use timer_create(). This allows you to get notified by a signal at a given time. You can then implement your action in the signal handler.
In any case you should be aware that the accuracy of course depends on the system clock accuracy.
First of all, you do not want to continuously check the time in a loop; that’s extremely inefficient and simply unnecessary.
Ok so you want to run some code at a given time in the future, as accurately as possible.
The simplest way is to simply start a background thread, compute how long until the target time (in the desired resolution) and then put the thread to sleep for that time period. When your thread wakes up, it executes the actual task. This should be accurate enough for the vast majority of needs.
The
std::chrono
library provides calls which make this easy:std::chrono
std::chrono
Here’s a snippet of code which does what you want using the system clock (which makes it easier to set a wall clock time):
On my laptop, the typical latency is about 2-3ms. If you use the
high_resolution_clock
you should be able to get even better results.There are other APIs you could use too, such as Boost where you could use ASIO to implement high res timeout.
Do you really need it to be accurate to the microsecond? Consider that at this resolution, you will also need to take into account all sorts of other factors, including system load, latency, clock jitter, and so on. Your code can start to execute at close to that time, but that’s only part of the problem.