首页 > 解决方案 > std::chrono::milliseconds .count() 以微秒为单位返回?

问题描述

我正在尝试记录一段时间内经过的毫秒数。

我有这样的课

// class member declarations
class MyClass {

    std::chrono::high_resolution_clock::time_point   m_start;
    std::chrono::system_clock::duration              m_elapsed;
};

我在课堂上有两种方法。一个是从 main 调用的func1CalledFromMainThread

// Class methods
using namespace std::chrono;
void MyClass::func1CalledFromMainThread() {

    m_start = std::chrono::high_resolution_clock::now();
}

另一个func2CalledFromADifferentThread是从不同的线程调用的

void MyClass::func2CalledFromADifferentThread() {

    // after some time following line of code runs from a different thread
    auto end = high_resolution_clock::now();

    m_elapsed = duration_cast<milliseconds>(end - m_start);
    std::cout << "Elapsed time in milliseconds is " << m_elapsed.count()/1000 << std::endl;
}

问题出在cout日志记录中。我看到我必须除以1000得到毫秒数m_elapsed。不count返回这里的计数std::chrono::milliseconds吗?我为什么要1000在这里除?count()总是返回microseconds还是我做错了?

标签: c++11chronomilliseconds

解决方案


count返回调用它的类型的刻度数。如果你这样写:

duration_cast<milliseconds>(end - m_start).count()

它会正确地给你毫秒数。但是,您没有将结果存储在 中std::chrono::milliseconds,而是将其存储在std::chrono::system_clock::duration(类型m_elapsed)中。因此,m_elapsed.count()返回 的频率中的滴答数,std::chrono::system_clock::duration在您的平台上可能是微秒。

换句话说,您milliseconds通过将结果存储在milliseconds.


推荐阅读