mal*_*lea 3 c++ timer c++11 c++-chrono
当我在下面编译此timer.hpp头文件时,编译器说:
错误:“ operator =”不匹配(操作数类型为“ std :: chrono :: _ V2 :: system_clock :: time_point {aka std :: chrono :: time_point>>}”和“ std :: __ success_type>> ::”输入{aka std :: chrono :: duration>}')end = std :: chrono :: high_resolution_clock :: now()-开始;
我猜开始和结束的变量类型是错误的。什么是正确的类型?我要用std::chrono::high_resolution_clock。
#include <chrono>
namespace timer{
static std::chrono::system_clock::time_point start, end;
void initTime(){
start = std::chrono::high_resolution_clock::now();
}
void endTime(){
end = std::chrono::high_resolution_clock::now() - start;
}
}
Run Code Online (Sandbox Code Playgroud)
应该将timer.hpp与某些主文件一起使用。
通过timer::initTime()在要测量的某个函数之前调用,然后timer::endTime()在该函数之后调用,我将获得计时结果(此处省略了持续时间的吸气剂)。
此代码有两个问题:
static std::chrono::system_clock::time_point start, end;
/* ... */
void endTime(){
end = std::chrono::high_resolution_clock::now() - start;
}
Run Code Online (Sandbox Code Playgroud)
您声明end为一个时间点,但是在赋值运算符的右侧,您要减去两个时间点(now()和start),并赋给end。
从逻辑上讲,如果减去两个时间点,则不会获得新的时间点。例如,如果我想减去“今天08:15:00”-“今天08:05:00”,则将结果描述为“今天00:10:00”是没有意义的。相反,C ++ chrono库具有duration类模板;它旨在表示时间长度(例如,两个时间点之间的差)。
请在operator -此处查看重载数字4:http:
//en.cppreference.com/w/cpp/chrono/time_point/operator_arith2
我建议观看@Howard Hinnant与上面链接的教程视频。Hinnant先生参与了std::chronoand boost::chrono库的开发。
潜在的第二个问题是starttype std::chrono::system_clock::time_point,它可能与返回的type std::chrono::high_resolution_clock::now()(具有type std::chrono::high_resolution_clock::time_point)不同(不同的时钟)。
| 归档时间: |
|
| 查看次数: |
1606 次 |
| 最近记录: |