how to get timestamp in c

后端 未结 5 1087
情话喂你
情话喂你 2021-01-19 10:53

I want to get timestamp for my log in c. i have written a function to get timestamp. But when i return the variable i m getting different value.

My code:

<         


        
5条回答
  •  难免孤独
    2021-01-19 11:20

    In answering this question I wanted a function that was simple, thread friendly, did not return a char* (which is often tedious to manage), thread-safe and could stand on its own feet. I have an aversion to functions that return char* or pointers that must be managed.

    The function below does not call malloc.

    The function takes no parameters and returns a timestamp. I think it works well.

    struct Timestamp {
        time_t seconds;
        long milliseconds;
        char timestring[32];
    };
    
    
    struct Timestamp getTimestamp()
    {
    char   timebuffer[32]     = {0};
    struct timeval  tv        = {0};
    struct tm      *tmval     = NULL;
    struct tm       gmtval    = {0};
    struct timespec curtime   = {0};
    
    struct Timestamp timestamp;
    
    int i = 0;
    
    // Get current time
    clock_gettime(CLOCK_REALTIME, &curtime);
    
    
    // Set the fields
    timestamp.seconds      = curtime.tv_sec;
    timestamp.milliseconds = round(curtime.tv_nsec/1.0e6);
    
    if((tmval = gmtime_r(×tamp.seconds, &gmtval)) != NULL)
    {
        // Build the first part of the time
        strftime(timebuffer, sizeof timebuffer, "%Y-%m-%d %H:%M:%S", &gmtval);
    
        // Add the milliseconds part and build the time string
        snprintf(timestamp.timestring, sizeof timestamp.timestring, "%s.%03ld", timebuffer, timestamp.milliseconds); 
    }
    
    return timestamp;
    }
    
    int main()
    {
        char   timebuffer[64]     = {0};
        int i = 0;
        struct timespec sleeptime = {0, 5000000L};
    
        struct Timestamp timestamp;
    
        for (i=0; i < 20; i++)
        {
            timestamp = getTimestamp();
            printf("Time is: %s \n", timestamp.timestring);
            nanosleep(&sleeptime, NULL);
        }
    
        return 0;
    }
    

提交回复
热议问题