C ++ GetTickCount()Elapsed Time与GetLocalTime不匹配 [英] C++ GetTickCount() Elapsed Time don't match with GetLocalTime

查看:110
本文介绍了C ++ GetTickCount()Elapsed Time与GetLocalTime不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在使用基于文件的历史记录系统,其功能是存储和检索一些历史信息。



在文件内部,我使用GetLocalTime()获取文件开始时间,将其存储在文件头中。然后我使用GetTickCount()将项目的时间偏移存储到文件中。

最后,我创建了一个工具来计算开始和偏移时间的绝对时间。

但我发现计算的时间与实际绝对时间不符。



例如:



假设我在10:30:28启动文件



Hi,

I am working on an File-based history system, whose function is to store and retrieve some history information.

Inside file, I use GetLocalTime() to get the File Start Time, store it on the file header. And then I use GetTickCount() to store the Time Offset of items into file.
Finally, I create a tool to calculate the absolute time with the start and the offset time.
But I found the calculated time is not match with the real absolute time.

for example:

Suppose I start the file at 10:30:28

DWORD x = GetTickCount();

void TimeoutWakeupFucntion()
{
  DWORD y = GetTickCount();

  DWORD Offset = (y >= x) ? (y - x) : (MAXDWORD - x + y);
 
  SYSTEMTIME st;
  GetLocalTime(&st);
}







然后

时间抵消真实绝对时间

1997 10:30:40.578

2995 10:30:41.583







184986 10:33:44.138



也就是说,计算出的时间总是比实际时间短。



有人知道什么是错的吗?



非常感谢你!




Then
Time Offset Real Absolute Time
1997 10:30:40.578
2995 10:30:41.583
.
.
.
184986 10:33:44.138

That is to say, the calculated time is always shorter than the real time.

Does anybody know what's wrong?

Thank you so much!

推荐答案

您正在使用两种不同的时间源。



GetTickCount()是一个单调计时器,以固定间隔递增而不进行任何调整,而 GetLocalTime()是一个受调整影响的实时时钟(Windows可能检测到不准确并添加每个滴答处的小偏移甚至将时钟与其他时间源(如NTP)同步。结果,实时时钟可能向前跳,甚至向后跳。



但我从未见过这么大的差异。您可以扩展程序以打印差异并在多个系统上运行更长时间以检查您的系统是否具有非常不准确的计时器。



最后的提示不是与您的问题相关:

您应该使用 GetSystemTime()而不是本地时间以UTC格式存储时间。然后,当夏令时变化时,实时跳转时没有问题。如果您想稍后显示时间,只需将它们转换为当地时间。
You are using two different kinds of time sources.

GetTickCount() is a monotonic timer that increments at fixed intervals without any adjustments while GetLocalTime() is a real time clock that is affected by adjustments (Windows may detect an inaccuracy and add small offsets at each tick or even synchronize the clock with other time sources like NTP). As a result, real time clocks may jump forward and even backward.

But I have never seen such big differences. You may extend your program to print the differences and run it for longer times on multiple systems to check if you have a system with very inaccurate timers.

A final tip not related to your question:
You should store times in UTC using GetSystemTime() rather than as local time. Then you did not have problems when the real time jumps when daylight saving time changes. If you want to display times later just convert them to local time.


这篇关于C ++ GetTickCount()Elapsed Time与GetLocalTime不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆