I ran an experiment to compare sleep/pause timing accuracy in python and C++
Experiment summary:
In a loop of 1000000 iterations, sleep 1 microsecond in each iteration.
Expected duration: 1.000000 second (for 100% accurate program)
In python:
import pause
import datetime
start = time.time()
dt = datetime.datetime.now()
for i in range(1000000):
dt += datetime.timedelta(microseconds=1)
pause.until(dt)
end = time.time()
print(end - start)
Expected: 1.000000 sec, Actual (approximate): 2.603796
In C++:
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
using usec = std::chrono::microseconds;
using datetime = chrono::_V2::steady_clock::time_point;
using clk = chrono::_V2::steady_clock;
int main()
{
datetime dt;
usec timedelta = static_cast<usec>(1);
dt = clk::now();
const auto start = dt;
for(int i=0; i < 1000000; ++i) {
dt += timedelta;
this_thread::sleep_until(dt);
}
const auto end = clk::now();
chrono::duration<double> elapsed_seconds = end - start;
cout << elapsed_seconds.count();
return 0;
}
Expected: 1.000000 sec, Actual (approximate): 1.000040
It is obvious that C++ is much more accurate, but I am developing a project in python and need to increase the accuracy. Any ideas?
P.S It's OK if you suggest another python library/technique as long as it is more accurate :)