c/c++ microsecond timestamp

bbc picture bbc · Mar 5, 2014 · Viewed 12.2k times · Source

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

Lorien Brune picture Lorien Brune · Sep 28, 2017

Something a bit shorter to try (C++):

using std::chrono;
__int64 microseconds_since_epoch = duration_cast<microseconds>(system_clock::now().time_since_epoch()).count();