How to get the current time in milliseconds from C in Linux?

前端 未结 7 936
不知归路
不知归路 2020-11-30 19:09

How do I get the current time on Linux in milliseconds?

7条回答
  •  伪装坚强ぢ
    2020-11-30 20:02

    This can be achieved using the POSIX clock_gettime function.

    In the current version of POSIX, gettimeofday is marked obsolete. This means it may be removed from a future version of the specification. Application writers are encouraged to use the clock_gettime function instead of gettimeofday.

    Here is an example of how to use clock_gettime:

    #define _POSIX_C_SOURCE 200809L
    
    #include 
    #include 
    #include 
    #include 
    
    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);
    }
    

    If your goal is to measure elapsed time, and your system supports the "monotonic clock" option, then you should consider using CLOCK_MONOTONIC instead of CLOCK_REALTIME.

提交回复
热议问题