c++11 - 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
还是我做错了?
解决方案
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
.
推荐阅读
- sql - 在“in”SQL Server 中计数
- java - Tomcat7 未在 CentOS 上启动
- python - 使用 Python 解析 PDF 文本的 Tika 无法处理垂直文本。有任何想法吗?
- java - 在 JDK 7 上运行的改造和 RxJava
- reactjs - 使用 serviceWorker 使用 React 制作 PWA
- extjs - 我无法在 viewController 中获取 Ext.MessageBox 的实例
- javascript - electron.remote 在渲染过程中未定义
- java - Kotlin 中 dl4j 的通用函数
- spring - 为构建管道配置fladdoodles嵌入式mongodb
- swift - 如何将对本地图像的引用插入到 html 并在标签中快速显示?