【发布时间】:2019-01-21 10:18:48
【问题描述】:
我正在尝试记录一段时间内经过的毫秒数。
我有这样的课
// class member declarations
class MyClass {
std::chrono::high_resolution_clock::time_point m_start;
std::chrono::system_clock::duration m_elapsed;
};
我在课堂上有 2 个方法。一个从 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 还是我做错了?
【问题讨论】:
-
由于您是从不同的线程访问
m_start,您应该查看std::mutex。 -
这是一个视频
<chrono>教程:youtube.com/watch?v=P32hvk8b13M -
@Angew。是的,我在实际代码中有互斥锁,它比这个例子复杂得多。我刚刚创建了一个示例代码来讨论和理解这个问题,而不涉及太多我认为有效的细节。非常感谢您的有用回答
标签: c++11 chrono milliseconds