clock_gettime API给出负值

时间:2015-08-10 04:48:14

标签: c linux operating-system timestamp

我希望当前的系统时间以微秒为单位,因此我使用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;
}

1 个答案:

答案 0 :(得分:-3)

希望以下代码可以帮助您:

    #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();
    }
相关问题