Reputation: 13
I know how to get current time with microsecond precision under linux using gettimeofday(). However it's not portable and does not work on MinGW. How to get the same functionality with C++11?
#include <sys/time.h>
#include <cstdio>
int main(){
timeval curTime;
gettimeofday(&curTime, NULL);
unsigned long micro = curTime.tv_usec;
printf("micro is: %lu\n", micro);
char buffer [30];
//localtime is not thread safe
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", localtime((const time_t*)&curTime.tv_sec));
printf("buffer is: %s\n", buffer);
char currentTime2[30] = "";
sprintf(currentTime2, "%s.%06Lu", buffer, micro);
printf("currenttime is: %s\n", currentTime2);
}
it's fine in Linux and does not print buffer under MinGW. What is wrong here?
Upvotes: 1
Views: 2072
Reputation: 64
Have you tried std::chrono::high_resolution_clock ? You might find this article a useful reference for the inner working of C++ 11 chrono library.
Upvotes: 2
Reputation: 275896
std::chrono::high_resolution_clock
. It is portable, but may suck. Duration cast into high precision: you can even ask how precise it claims to be, but that may not be trustworthy.
boost
has clock and time libraries that are portable, and may be more reliable.
Upvotes: 2