首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何从Linux的C中获取毫秒级的当前时间?

如何从Linux的C中获取毫秒级的当前时间?
EN

Stack Overflow用户
提问于 2018-03-01 06:59:17
回答 2查看 0关注 0票数 0

如何在毫秒内获得Linux上的当前时间?

EN

回答 2

Stack Overflow用户

发布于 2018-03-01 15:56:53

这是一个如何使用clock_gettime的例子:

代码语言:javascript
复制
#define _POSIX_C_SOURCE 200809L

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

void print_current_time_with_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
    if (ms > 999) {
        s++;
        ms = 0;
    }

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

如果您的目标是测量已用时间,并且您的系统支持“单调时钟”选项,那么您应该考虑使用CLOCK_MONOTONIC而不是CLOCK_REALTIME

票数 0
EN

Stack Overflow用户

发布于 2018-03-01 16:00:21

你值得这样试下,我反正觉得这种方法很好:

代码语言:javascript
复制
struct timeval  tv;
gettimeofday(&tv, NULL);

double time_in_mill = 
         (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ; // convert tv_sec & tv_usec to millisecond
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档