Tuesday, January 31, 2017

Getting Timestamp in microsecond range in C++

#include <sys/time.h>

void Log(const char* szMsg)
{
// let's get the time stamp
struct timeval tvNow;
gettimeofday(&tvNow, 0);
struct tm* lt = localtime(&tvNow.tv_sec);

// open log file for append, print, and save
FILE* fp = fopen("/tmp/itfm.log", "a");
fprintf(fp, "[%d-%d-%d %d:%d:%d.%06ld] %s", lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec, tvNow.tv_usec, szMsg);
fclose(fp);
}

Note:
1. tvNow.tv_usec is in %06ld to strictly shift it at microsecond resolution; the "ld" identifies it as "long int" since tv_usec is declared as "long int" type; some compilers will trigger warning if you use other format such as "d" or "l"
2. timeval structure is declared in sys/time.h

No comments:

Post a Comment