我知道如何在 linux 下使用 gettimeofday() 以微秒精度获取当前时间。但是它不可移植并且不能在 MinGW 上运行。如何使用 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);
}
在 Linux 下没问题,在 MinGW 下不打印缓冲区。这里有什么问题?
最佳答案
std::chrono::high_resolution_clock
。它是可移植的,但可能很烂。将持续时间转化为高精度:您甚至可以问它声称有多精确,但这可能不可信。
boost
具有可移植的时钟和时间库,并且可能更可靠。
关于c++11 以微秒精度获取当前时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29269129/