i just want to make some computations every 20 ms but
int main(){
auto start = std::chrono::high_resolution_clock::now();
auto finish = std::chrono::high_resolution_clock::now();
for(int i = 0;i<= 1000;i++) {
//Do some fancy stuff which last less then 20 ms
std::this_thread::sleep_until(finish + std::chrono::microseconds(20000));
finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> ms_double = finish - start;
std::cout << ms_double.count() << "ms\n";
start = finish;
}
}
Output:
...
23.3334ms
23.3336ms
23.3349ms
23.3338ms
23.3369ms
23.3309ms
23.334ms
23.3336ms
23.3336ms
23.3349ms
23.3322ms
23.3342ms
...
Question
How can i archive better accuracy ?
When i change it to:
std::this_thread::sleep_until(finish + std::chrono::microseconds(19000));
or
std::this_thread::sleep_until(finish + std::chrono::microseconds(18000));
Output now in both cases:
...
19.9987ms
20.0004ms
20.0004ms
19.9985ms
20.0233ms
19.9863ms
19.9948ms
20.0089ms
19.9927ms
19.9971ms
19.9992ms
20.0021ms
...
Is this a Scheduler Problem ?
Additional Information##
I have made the same with POSIX Timer, but when i add the calculation and Sensor communication to the loop, the standard deviation is exploding to 0.8 ms. With thread::sleep i archive a standard deviation of 0.02 ms (Calculation and Communication Duration <10ms in both cases)