I need to perform a specific function once every 20 мс passed after executing it (for example). To do this, I put a mark after its implementation:functime = std::chrono::high_resolution_clock::now(); Then some more actions are performed (checked, they are performed in a few microseconds). Accordingly, before the next call of this function, I pause as follows:
if (std::chrono::milliseconds(20) > (std::chrono::high_resolution_clock::now() - functime)) { std::this_thread::sleep_for(std::chrono::milliseconds(20) - (std::chrono::high_resolution_clock::now() - functime)); } But as a result of the check, it turns out that it is performed every 0.031201 секунды , and not 0.020000 . Why is that?
PS before I made changes to the code of this program, but in general not related to this, everything worked fine. I work in VS2013.
UPDATE1 This function, which is called, is a function to send RTP packets that must be sent every 20 мс . Several "clients" are connected to the program, who themselves send the same RTP packets (data is received in separate streams in the number of clients). sending data was assumed in their parent stream, so as not to load the CPU with a data availability check. Accordingly, before sending, the incoming packets are processed, and then they are sent back to all clients also once in 20 мс (respectively, a pause is needed only before sending to the first client, which freezes the next data processing for 20 мс , too, which is required for normal operation). And, although data processing takes less than a microsecond, now I have a delay instead of 20 мс - 31,2 .
UPDATE2 I found out that the computer is dumb . In the test project:
int main() { using namespace std::chrono; for (int i = 0; i < 100; ++i) { steady_clock::time_point t1 = steady_clock::now(); std::this_thread::sleep_for(std::chrono::milliseconds(20)); steady_clock::time_point t2 = steady_clock::now(); duration<double> time_span = duration_cast<duration<double>>(t2 - t1); std::cout << " " << time_span.count(); } system("pause"); return 0; } Writes that in ba = 31. Sometimes 32 ... Is there any way to do the same, but without std::this_thread::sleep_for ?
I tried replacing it with boost::this_thread::sleep_for(boost::chrono::milliseconds(20)); the result is random in the range of 15 to 32 .
Perversions of the form (with various methods of implementation ( steady_clock , etc.)):
int main() { auto a = GetTickCount(); while ((GetTickCount() - a) < 20) { ; } cout << GetTickCount() -a; system("pause"); return 0; } Also gives the result of 31-32 ...
Setting real-time priority only increased latency.
sleep_forguarantees a sleep time of at least specified. More is allowed. - Kromster