简体   繁体   English

使用 chrono 库获取不准确的系统时间

[英]Get system time not accurate by using chrono library

I am sampling the system time at 500ms intervals using std::chrono.我使用 std::chrono 以 500 毫秒的间隔对系统时间进行采样。 On each sample, I subtract the current time from the last time, and accumulate the result.在每个样本上,我从上次时间中减去当前时间,并累加结果。 However after 1hr, the total accumulated time is about 50ms faster for an hour.然而,在 1 小时后,总累积时间比一个小时快了大约 50 毫秒。 Does anybody know the reason?The code of get system time as below:有人知道原因吗?获取系统时间的代码如下:

void serverTimeResponse(long serverTime) {        
     long localTime =(long)std::chrono::duration_cast<std::chrono::microseconds(now.time_since_epoch()).count();        
      long duration = localtime - serverTime;        
    writeToCsvFile(duration); 

} 

The serverTimeResponse will be called every 500ms because server will return by socket, I record the duration into csv file, after 1 hour, I see the last row duration is more 50ms than the first row duration in csv file. serverTimeResponse 将每 500 毫秒调用一次,因为服务器将通过套接字返回,我将持续时间记录到 csv 文件中,1 小时后,我看到最后一行持续时间比 csv 文件中第一行持续时间多 50 毫秒。 I doubt whether the chrono library has some issue for get the system time.我怀疑 chrono 库是否有获取系统时间的问题。

Ran on ubuntu 18.04运行于 ubuntu 18.04

I can understand what you are trying to achieve, but you may be running into issues relating to the OS's thread scheduling.我能理解您要实现的目标,但您可能遇到了与操作系统线程调度相关的问题。 You have not produced a minimal reproducible example, so I assume you are using eg:您还没有生成最小的可重现示例,因此我假设您使用的是例如:

std::this_thread::sleep_for(500ms);

If this is the case, then you are at the mercy of the OS to sleep for the correct amount of time.如果是这种情况,那么您将受操作系统的支配,以睡眠正确的时间。

Every 500ms you sample the current time and subtract the last time, this sounds fine.每 500 毫秒采样一次当前时间并减去上一次时间,这听起来不错。 However, when you sleep for 500ms, the OS schedules the program to be woken up sometime around that number.但是,当您休眠 500 毫秒时,操作系统会安排程序在该数字附近的某个时间被唤醒。 Remember, OS's are NOT REAL TIME.请记住,操作系统不是实时的。 They have no guarantees that your application will sleep for EXACTLY 500ms.他们无法保证您的应用程序会休眠 500 毫秒。

All of these small sleep discrepancies of time between your samples will add up.您的样本之间所有这些微小的睡眠时间差异都会加起来。 Below are some calculations:下面是一些计算:

You are sampling every 500ms for 1hr:

1000ms * 60s * 60m = 3600000ms  // 1hr in milliseconds
3600000ms / 500ms = 7200        // 7200 samples @ 500ms each
50ms / 7200 =  0.006944444ms    // or 6.944444us error per sample

As you can see, there is a tiny error of 6.9us.如您所见,存在 6.9us 的微小误差。 So the OS almost slept for 500ms, but didn't quite.所以操作系统几乎休眠了 500 毫秒,但并不完全。 These small errors add up, and there isn't a whole lot you can do when it comes to EXACT sleeps.这些小错误加起来,就 EXACT 睡眠而言,您无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM