如何计算精确的时差(C ++)? [英] How can I calculate a precise time difference (C++)?

查看:79
本文介绍了如何计算精确的时差(C ++)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个UTC时间,分别存储为 day:hour:minute:second:millisecond,也存储为day,hour,min等的五个整数变量。我想找到两者之间的区别次,精确到毫秒。

I have two UTC times, stored as "day:hour:minute:second:millisecond", and also as five integer variables for day, hour, minute, etc. I'd like to find the difference between the two times, with millisecond precision. How can this be done in C++?

推荐答案

以毫秒精度计算时差:


  1. 将两个时间戳都转换为 std :: chrono :: system_clock :: time_point

 struct std::tm thetime  { .tm_sec = sec, .tm_min = min, .tm_hour = hour,
                           .tm_mday = mday, .tm_mon = mon, .tm_year = year };

 auto mytime = (std::chrono::system_clock::from_time_t(std::mktime(&thetime)))
       + std::chrono::milliseconds(msec);



  • 减去两个生成的时间戳。

  • Subtract the two resulting timestamps.

     auto diffms = std::chrono::duration_cast<std::chrono::milliseconds(mytime2 - mytime1).count();
    



  • 编辑:这不考虑跳跃秒或夏令时。如果您对毫秒感兴趣,则可能应该使用既不包含毫秒的时间刻度(因此,本地时间和UTC都不是不错的选择)。如果您的日期和时间是从 UTC获得的,首先,POSIX时钟很不错,因为 UTC POSIX时钟不代表leap秒(当然也没有DST)。

    this does not take into account leap seconds or daylight saving time. If you are interested in milliseconds, you should probably use a time scale which has neither of these (so neither local time nor UTC are good choices). If your date and time were derived from a "UTC" POSIX clock in the first place, you are probably good to go, since "UTC" POSIX clock doesn't account for leap seconds (and of course has no DST).

    这篇关于如何计算精确的时差(C ++)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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