【问题标题】:c++11 get current time with microsecond precisionc ++ 11以微秒精度获取当前时间
【发布时间】:2015-05-29 22:02:46
【问题描述】:

我知道如何在 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 下不打印缓冲区。这里有什么问题?

【问题讨论】:

  • 任何操作系统?
  • auto now = std::chrono::system_clock::now(); 你可以以任何你想要的分辨率提取。
  • @red 在ns 中要求它不会给你ns 分辨率。
  • @Yakk 没错,尽管它至少会以ns 格式提供给您。使用 HR 时钟的问题在于它不能保证与系统时钟相关联(如果它具有更高的分辨率,它将选择 steady_clock),这使得它无法可靠地获取一天中的时间。
  • 需要亚毫秒级精度的时间通常是一个危险信号。通常唯一需要如此精确的就是时间interval。绝对时间仅在将该时间与其他时钟的时间进行比较时才重要,这意味着网络通信。网络通常具有毫秒级的延迟。

标签: c++ c++11 ctime


【解决方案1】:

std::chrono::high_resolution_clock。它是便携式的,但可能很糟糕。持续时间投射到高精度:你甚至可以问它声称有多精确,但这可能不可信。

boost 具有可移植的时钟和时间库,并且可能更可靠。

【讨论】:

    【解决方案2】:

    你试过 std::chrono::high_resolution_clock 吗? 您可能会发现这个article 是关于内部工作的有用参考 C++ 11 计时库。

    【讨论】:

    • 我有那本书,仍然找不到例子来抽时间。 high_resolution_clock 没有 to_time_t()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2011-07-15
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多