【问题标题】:clock_gettime API is giving negative valuesclock_gettime API 给出负值
【发布时间】:2015-11-01 21:49:43
【问题描述】:

我想要以微秒为单位的当前系统时间,所以我使用 clock_gettime 编写了一个程序,但它有时会返回负值。有人可以帮我解决这个问题。

int main(void) {
    struct timespec tms;

        /* The C11 way */
        /* if (! timespec_get(&tms, TIME_UTC)) { */

        /* POSIX.1-2008 way */
        if (clock_gettime(CLOCK_REALTIME,&tms)) {
                    return -1;
             }
            /* seconds, multiplied with 1 million */
            long long micros = tms.tv_sec * 1000000;
                /* Add full microseconds */
                micros += tms.tv_nsec/1000;

                printf("Microseconds: %lld\n",micros);
                return 0;
}

【问题讨论】:

  • 你不应该使用%llu吗?
  • 查看time_t的大小(tv_sec的类型)。如果你为 32 位 Linux 编译,它只会是 32 位。
  • 为了扩展@Mat 的准确评论,您应该写1000000LL 以强制将乘法作为long long 完成。如果time_t是32位类型,则乘法将作为32位乘法(有溢出)进行,(溢出)结果之后会转换为long long
  • 哦,好吧。我得到了它。有效。谢谢。
  • @Devendar 如果您找到了解决方案,请考虑为您的问题添加答案。这将有助于 StackOverflow,它首先帮助了您。

标签: c linux operating-system timestamp


【解决方案1】:

希望以下代码对您有所帮助:

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

    void get_time_in_ms()
    {
        long ms;
        time_t time;
        struct timespec spec;
        char tm[14];

        clock_gettime(CLOCK_REALTIME, &spec);

        time  = spec.tv_sec;
        ms = round(spec.tv_nsec / 1000000 ); // Convert nanoseconds to milliseconds

        printf("Current time: %lu.%03ld seconds since the Epoch\n", time, ms);
        sprintf(tm,"%lu%03ld",time, ms);
        printf("Time : %s\n", tm);
    }

    void main() {
            get_time_in_ms();
    }

【讨论】:

  • 问题是寻找一个代表自纪元以来微秒数的单个数字(然后打印该值以验证它)。这个答案提供了自纪元以来的毫秒数,而不是作为单个数字给出。
猜你喜欢
  • 2013-07-16
  • 2012-08-27
  • 2012-03-04
  • 2016-12-29
  • 2023-04-04
  • 2020-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多