Implementing <1ms latency on Windows in C ++

I've been self-educating C ++ for almost a week now to continue my upcoming C ++ course at university. I am now on this project where I am trying to figure out if I can implement the exact latency or hibernation under 1ms.

I am a little bit into how to implement this on Windows and have seen answers like:

  • Sleep is inaccurate
  • Can't sleep less than 1ms on windows, but possible on UX platforms.
  • Use boost library in C ++

So I tried to get boost library in visual studio 2013 and found this C ++ snippet Implementing temporary callback function by gob00st

I changed 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 will give exactly 10000 after 10 seconds, so it looks like I'm still sticking to this limit on windows you can't sleep or delay less than 1ms.

I then found this answer saying that I can use the Boost processor precision timer to achieve this. Accurate delays between notes when synthesizing a song

How do I edit the code snippet to use the Cpu precision timer instead of using the asio accelerator?

+3


source share


2 answers


There are two different synchronization problems. One is accurate timing. which can be achieved on modern computers by means of a boost or a new standard chronograph. Another issue is related to sleeping, waking up, switching threads, etc. OS support is needed here. The fastest you usually get here is 1ms. More recently, it has ranged from 10ms to 20ms. If you need shorter latencies than the OS provides, you cannot sleep. instead, you must "write" the time in your own loop.



+2


source


Windows has a high performance counter API.

You need to get the shape of the ticks QueryPerformanceCounter

and divide by the cpu frequency provided QueryPerformanceFrequency

.



There is a so-called HPET timer . The High Precision Event Timer (HPET) was jointly developed by Intel and Microsoft to meet the timing requirements for multimedia and other time-sensitive applications. HPET support on Windows with Windows Vista, and Windows 7 and Windows 8 hardware certifications require HPET support on the hardware platform.

In your specific case, you can use timeGetTime

which only has ms precision.

+1


source







All Articles