我有一个程序可以从系统时钟读取当前时间并将其保存到一个文本文件中。我以前使用的是 GetSystemTime 函数,但时间并不完全一致,例如:一个时间是 32567.789,下一个时间是 32567.780,时间倒退。
我正在使用这个程序每秒节省 10 次时间。我读到 GetSystemTimeAsFileTime 函数更准确。我的问题是,如何将当前代码转换为使用 GetSystemTimeAsFileTime 函数?我尝试使用 FileTimeToSystemTime 函数,但遇到了同样的问题。
SYSTEMTIME st;
GetSystemTime(&st);
WORD sec = (st.wHour*3600) + (st.wMinute*60) + st.wSecond; //convert to seconds in a day
lStr.Format( _T("%d %d.%d\n"),GetFrames() ,sec, st.wMilliseconds);
std::wfstream myfile;
myfile.open("time.txt", std::ios::out | std::ios::in | std::ios::app );
if (myfile.is_open())
{
myfile.write((LPCTSTR)lStr, lStr.GetLength());
myfile.close();
}
else {lStr.Format( _T("open file failed: %d"), WSAGetLastError());
}
编辑 为了添加更多信息,代码从每秒运行 10 次的相机捕获图像,并将拍摄图像的时间保存到文本文件中。当我从第二个减去文本文件的第一个条目时,依此类推,例如:条目 2-1 3-2 4-3 等我得到这个图,其中 x 轴是条目数,y 轴是减去的值。
它们中的大多数都应该在 0.12 左右。但是,您可以看到它们中的很多都不同,有些甚至为负数。这不是相机的原因,因为相机有自己的内部时钟并且没有变化。它与捕获系统时间有关。我想要的是最准确的方法,以最高分辨率和尽可能少的噪音提取系统时间。
编辑 2 我已采纳您的建议并再次运行该程序。这是结果:
如您所见,它比以前好多了,但仍然不对。我觉得很奇怪,它似乎是渐进式的。我也刚刚绘制了时间,这是结果,其中 x 是条目,y 是时间:
有没有人知道什么可能导致时间每 30 帧左右消失一次?
最佳答案
首先,你想要得到FILETIME
如下
FILETIME fileTime;
GetSystemTimeAsFileTime(&fileTime);
// Or for higher precision, use
// GetSystemTimePreciseAsFileTime(&fileTime);
根据 FILETIME
的 documentation ,
It is not recommended that you add and subtract values from the FILETIME structure to obtain relative times. Instead, you should copy the low- and high-order parts of the file time to a ULARGE_INTEGER structure, perform 64-bit arithmetic on the QuadPart member, and copy the LowPart and HighPart members into the FILETIME structure.
那么,接下来你应该做的是
ULARGE_INTEGER theTime;
theTime.LowPart = fileTime.dwLowDateTime;
theTime.HighPart = fileTime.dwHighDateTime;
__int64 fileTime64Bit = theTime.QuadPart;
就是这样。 fileTime64Bit
变量现在包含您要查找的时间。
如果你想获得一个 SYSTEMTIME
对象,你可以执行以下操作:
SYSTEMTIME systemTime;
FileTimeToSystemTime(&fileTime, &systemTime);
关于C++初学者如何使用GetSystemTimeAsFileTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470442/