mercredi 25 mars 2015

c++11 get current time with microsecond precision

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?


Aucun commentaire:

Enregistrer un commentaire