Reputation: 425
For almost a week now I've been self-studying c++ to advance study on my upcoming c++ course in the university. Now I'm at this project of mine where I'm trying to see if I can implement an accurate delay or sleep for less than 1ms.
I've research for a bit on how to implement this in windows and has been seeing answers like:
So I tried getting the boost library in visual studio 2013 and found this snippet c++ Implementing Timed Callback function by gob00st
I modified the deadline class a bit:
class Deadline
{
int i = 0;
public:
Deadline(deadline_timer &timer) : t(timer) {
wait();
}
void timeout(const boost::system::error_code &e) {
if (e)
return;
cout << i++ << endl;
wait();
}
then changed this line
void wait() {
t.expires_from_now(boost::posix_time::seconds(1)); //repeat rate here
t.async_wait(boost::bind(&Deadline::timeout, this, boost::asio::placeholders::error));
}
to these
void wait() {
t.expires_from_now(boost::posix_time::microseconds(100)); //repeat rate here
t.async_wait(boost::bind(&Deadline::timeout, this, boost::asio::placeholders::error));
}
Run it and it output exactly the number 10000 after 10 seconds, so it looks like I'm still stuck on this restriction in windows that you can't sleep or delay for less than 1ms.
Then I found this answer saying I can use Boost's CPU precision timer to achieve this. Accurate delays between notes when synthesising a song
How would I edit the code snippet to use the Cpu precision timer instead of using boost's asio timer?
Upvotes: 3
Views: 1768
Reputation: 3749
There are two different issues with timing. One is accurate measurement of time. that can be achieved on modern computers via boost or new standard chrono. The other issue is related to sleep, wake-up, thread switch and so on. here support of the OS is needed. The fastest you usually get here is 1ms. Not long ago it was in the range of 10ms to 20ms. If you need shorter delays than provided by the OS you cannot sleep. instead you have to 'burn' the time in yor own loop.
Upvotes: 2
Reputation: 6556
Windows has a High-Performance Counter API.
You need to get the ticks form QueryPerformanceCounter
and divide by the frequency of the processor, provided by QueryPerformanceFrequency
.
There is also so called HPET Timer. The High Precision Event Timer (HPET) was developed jointly by Intel and Microsoft to meet the timing requirements of multimedia and other time-sensitive applications. HPET support has been in Windows since Windows Vista, and Windows 7 and Windows 8 Hardware Logo certification requires HPET support in the hardware platform.
For your particular case you can use timeGetTime
which only has ms precision.
Upvotes: 1