Search code examples
clinuxoperating-systemunix-timestamptimestamp-with-timezone

In C, How to get full timestamp (even after seconds) in linux?


I get a stream of bytes, after each 2000 bytes, I want to create a new file and store it. as it is a continuous stream of bytes, I cant use counter etc. So, I want to use system time stamp to identify file uniquely like filename.

I found some threads to get system time stamp, but there I am seeing till seconds. Is there any other way, with which we can get full timestamp in C, linux OS (timestmap like: 2011-11-08 18:02:08.954092000)? In all thread, I am seeing only till seconds like 2011-11-08 18:02:08


Solution

  • Linux has clock_gettime() with nanosecond resolution.

    Example code

    #include <stdio.h>
    #include <time.h>
    
    int main(void) {
        unsigned mult = 0;
        struct timespec t0, t1;
        clock_gettime(CLOCK_REALTIME, &t0);
        for (unsigned k = 0; k < 10000000; k++) mult *= k; // no overflow!
        clock_gettime(CLOCK_REALTIME, &t1);
    
        printf("%lld.%09ld --> %lld.%09ld\n",
              (long long)t0.tv_sec, t0.tv_nsec,
              (long long)t1.tv_sec, t1.tv_nsec);
        return 0;
    }
    

    On my machine (FreeBSD/Unix but should be the same as any Linux), the code above prints

    1438167485.022409606 --> 1438167485.055779608