c++11 以微秒精度获取当前时间

标签 c++ c++11 ctime

我知道如何在 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/

相关文章:

c++ - 两个用户输入时间的差异c++

c++ - 当我没有参数时,如何从时间戳显示时间并显示当前时间?

c++ - C++ 中 Armadillo 矩阵维度的动态参数化

c++ - 捕获未分配的 r 值的编译器选项

c++ - 转换为 const vector

c++ - 为什么 =default on operator= 在有 const 成员时编译?

c - 有人为 MSP430 的 IAR Embedded Workbench 实现了 __getzone() 吗?

c++ - 在数学上添加两个字符串?

c++ - 是否存在连续存储的 HashMap 数据结构?

c++ - 模板参数包 : How to create a Tuple of an independent type with same length