C: gettimeofday() produces the same value every run

732 Views Asked by At

I'm trying to print the time in ISO-8601 with decisecond precision. YYYY-MM-DDThh:mm:ss.s

Here is my code:

#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void milli_time(char* dest, struct timeval* t)
{
    struct tm* timeInfo;
    strftime(dest, 22, "%Y-%m-%dT%t", localtime(&t->tv_sec));
    printf("%s\n", dest);
    fflush(stdout);
    char deciTime[3];
    sprintf(deciTime, ".%lu", ((t->tv_usec)/100000ul));

    strcat(dest, deciTime);
}

int main()
{
    struct timeval* theTime;
    char timeString[32];
    gettimeofday(theTime, NULL);
    printf("%lu.%lu\n", theTime->tv_sec, theTime->tv_usec);
    milli_time(timeString, theTime);
    printf("%s\n", timeString);
    fflush(stdout);
}

And the output every time I run it is:

134520616.3077826840
1974-04-06T17:50:16
1974-04-06T17:50:16.30778

The other thing I notice is that tv_usec is greater than one million.

1

There are 1 best solutions below

0
On BEST ANSWER

Change struct timeval* theTime to struct timeval theTime and update the corresponding references to it:

gettimeofday(&theTime, NULL);
// etc

This way you're allocating the space for the struct, rather than just a pointer to the struct. Your code segfaults when I try to run it on my machine.