【问题标题】:How to get the difference of time stamps having milliseconds portion using C in Linux?如何在 Linux 中使用 C 获得具有毫秒部分的时间戳的差异?
【发布时间】:2022-08-14 07:46:25
【问题描述】:

我需要找出格式为YYYY DD MM HH MM SS MSC 的2 个时间戳的区别。 例如2022 08 13 08 17 20 5122022 08 13 08 17 20 000 的差异应该返回512 msec
我浏览了https://stackoverflow.com/questions/9076494/how-to-convert-from-utc-to-local-time-in-c#:~:text=Or-,strptime(datetime%2C%20%22%25A%20%25B%20%25d%20%25,)%3B%20printtime%3Dctime(%3C)%3B 中的帖子。
mktime 使用 struct tm pointer 可以代表直到 seconds 分辨率。

我们应该使用哪个函数来包含milliseconds 部分以及计算?我的测试系统有ubuntu 18.04 版本。

  • 2 time stamps having format 时间戳在哪个时区? has provision to represent till seconds resolution. soooo 自己处理秒数和毫秒数?我不明白。 Which function should we use to include milliseconds portion as well for computation ?自己写一个?在mktime 之后只是seconds * 1000 + millisecondsHow to get the difference of time stamps having milliseconds portion using C in Linux? 以毫秒为单位表示时间。减去。
  • @KamilCuk 时间戳位于 UTC 时区。我在想如果任何系统功能已经可用,我可以使用它们。
  • are in UTC time zone 所以记得在调用mktime 之前设置时区。 I was thinking if any system function is already available 没有。对于 glibc,timersub 对应于 struct timeval。还有更好的struct timespec,但没有我知道的功能。

标签: linux time difference epoch


【解决方案1】:

C 提供difftime 来计算秒数,timegm 有助于 UTC 时区。注意那个棘手的tm_mon 元素(自一月以来的月数,所以八月实际上是 7 而不是 8)。

也许通过添加毫秒差异来扩展 difftime 的结果?

像这样的东西?

#include <stdio.h>
#include <time.h>
#include <unistd.h>

struct TIME {
  struct tm tm;
  unsigned int tm_msec;
};

double difftime_ms( struct TIME *time2, struct TIME *time1 )
{
  time_t t1 = timegm( &time1->tm );
  time_t t2 = timegm( &time2->tm );
  return ( 1000.0 * difftime( t2, t1 ) + ( time2->tm_msec - time1->tm_msec ) );
}

int main()
{
  struct TIME time1 = { .tm = { .tm_year = 2022, .tm_mon = (8-1), .tm_mday = 13, .tm_hour = 8, .tm_min = 17, .tm_sec = 20} , .tm_msec = 000 };
  struct TIME time2 = { .tm = { .tm_year = 2022, .tm_mon = (8-1), .tm_mday = 13, .tm_hour = 8, .tm_min = 17, .tm_sec = 20} , .tm_msec = 512 };

  printf( "Difference is %.2f msec\n", difftime_ms( &time2, &time1 ) );
  return 0;
}

【讨论】:

    猜你喜欢
    • 2021-04-08
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多