我需要最快的方法来获得本地时间(因此考虑到当前时区),至少以毫秒为单位,如果可以以十分之一毫秒为单位,那就更好了。
我想避免使用gettimeofday(),因为它现在是一个过时的函数。
所以,似乎我需要使用clock_gettime(CLOCK_REALTIME, ...)并将小时调整到当前时区,但如何调整?最好的办法是什么?在存储时钟获取的时间戳之前,还是在将其转换为当前时区的公历之前?
编辑:我最初的加入get_clock和localtime的示例-有更好的方法达到这个目的吗?

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

int main() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);

    struct tm* ptm;
    ptm = localtime(&(ts.tv_sec));

    // Tenths of milliseconds (4 decimal digits)
    int tenths_ms = ts.tv_nsec / (100000L);

    printf("%04d-%02d-%02d %02d:%02d:%02d.%04d\n",
        1900 + ptm->tm_year, ptm->tm_mon + 1, ptm->tm_mday,
        ptm->tm_hour, ptm->tm_min, ptm->tm_sec, tenths_ms);
}

最佳答案

是的,这可以通过使用clock_gettime()函数来实现。在当前版本的POSIX中,gettimeofday()被标记为已过时。这意味着它可能会从规范的未来版本中删除。鼓励应用程序编写器使用clock_gettime()函数而不是gettimeofday()
长话短说,下面是一个如何使用clock_gettime()的示例:

#define _POSIX_C_SOURCE 200809L

#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <time.h>

void print_current_time_in_ms (void)
{
    long            ms; // Milliseconds
    time_t          s;  // Seconds
    struct timespec spec;

    clock_gettime(CLOCK_REALTIME, &spec);

    s  = spec.tv_sec;
    ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds

    printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n",
           (intmax_t)s, ms);
}

如果您的目标是测量经过的时间,并且您的系统支持“单调时钟”选项,那么您应该考虑使用CLOCK_MONOTONIC而不是CLOCK_REALTIME
还有一点,在试图编译代码时记住要包含-lm标志。
要获取时区,请执行以下操作:
#define _GNU_SOURCE /* for tm_gmtoff and tm_zone */

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

int main(void)
{
  time_t t = time(NULL);
  struct tm lt = {0};

  localtime_r(&t, &lt);

  printf("Offset to GMT is %lds.\n", lt.tm_gmtoff);
  printf("The time zone is '%s'.\n", lt.tm_zone);

  return 0;
}

注意:time()返回的从epoch开始的秒数是以GMT(格林威治标准时间)为单位测量的。

关于c - 获取本地时间(以毫秒为单位),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42792633/

10-12 00:16
查看更多