I am working on high accuracy timers in C++ on Windows. My application requires the timer accuracy in ms. Up to 5 ms error can be omitted in the app. I have shared the code below and I have got very good repeatability in this timer. 2 times out of 20 were error but the errors are quite big around 75 ms. What can be caused of these errors? Because whenever I run the program the error level is the same which is around 75 ms. I usually choose delay 10 ms. Is it possible to obtain ms accuracy on Windows? Thank you in advance.
#include <string>
#include <chrono>
#include <iostream>
using namespace std;
//Get the time stamp
time_t getTimeStamp()
{
std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds> tp =
std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now());
auto tmp = std::chrono::duration_cast<std::chrono::milliseconds>(tp.time_since_epoch());
time_t timestamp = tmp.count();
return timestamp;
}
//Get the time year-month-day hour-minute-second millisecond
std::string gettm(__int64 timestamp)
{
__int64 milli = timestamp + (__int64)8 * 60 * 60 * 1000;
auto mTime = std::chrono::milliseconds(milli);
auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(mTime);
auto tt = std::chrono::system_clock::to_time_t(tp);
std::tm now;
::gmtime_s(&now, &tt);
char res[64] = { 0 };
sprintf_s(res, _countof(res), "%03d",static_cast<int>(milli % 100));
return std::string(res);
}
int main(void)
{
bool state = false;
int delay;
cout << "Delay (ms): " << endl;
cin >> delay;
Again:
string now = gettm(getTimeStamp());
int now_int = stoi(now);
int sss = now_int + delay;
if (sss >= 100)
sss = sss % 100;
while(1)
{
string change = gettm(getTimeStamp());
int now_change = stoi(change);
if (now_change >= 100)
now_change = now_change % 100;
state = true;
cout << "High O4 and now (ms): "<< sss << " and change (ms): "<<now_change <<endl;
if (now_change == sss)
{
state = false;
cout << "Low O4" << endl;
goto Again;
}
}
return 0;
}