bbc bbc - 1 year ago 366
C Question

c/c++ microsecond timestamp

I used this piece of code to get timestamp in microsecond in c/c++. but it doesn't look like microsecond. also i don't know if there is any way to format it.

timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
unsigned long micro = curTime.tv_usec*(uint64_t)1000000+curTime.tv_usec;

char buffer [80];
//localtime is not thread safe
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));

char currentTime[84] = "";
char currentTime2[80] = "";
sprintf(currentTime, "%s:%3d", buffer, milli);
sprintf(currentTime2, "%s:%Lu", buffer, micro);
printf("time %s, hptime %s\n", currentTime, currentTime2);

and what is the right format to output it? Thank you!

Answer Source

The typical printing format for sub-second times uses the decimal indicator (. in many locales) and so 59 and some seconds might look like 59.00013.

The micro variable you created takes the current microsecond count, multiplies it by 1000000 then adds the current microsecond count again; I expect that you intend to either use the microsecond count alone, or together with the count of seconds:

unsigned long micro = curTime.tv_usec*(uint64_t)1000000+curTime.tv_usec;

should be written as

unsigned long micro = curTime.tv_sec*(uint64_t)1000000+curTime.tv_usec;

to get seconds and microseconds together in the same number.

To write this into your output, you might consider changing the line

sprintf(currentTime2, "%s:%Lu", buffer, micro);


sprintf(currentTime2, "%s.%Lu", buffer, curTime.tv_usec);

Using the altered micro definition, you can also output

sprintf(currentSeconds, "%.6f", micro / 1000000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download