使用标准::时间::high_resolution_clock时"operator ="不匹配

No match for "operator =" when using std::chrono::high_resolution_clock

本文关键字:operator 不匹配 clock 时间 high resolution 标准      更新时间:2023-10-16

当我编译此 timer.hpp 标头文件时,编译器说:

错误:" operanter ="没有匹配(操作数类型为 ‘std :: chrono :: _ v2 :: system_clock :: time_point {aka std :: chrono :: time_point>>}’和 ‘std :: __ success_type>>> :: type {aka std :: chrono ::持续时间>}( end = std :: chrono :: high_resolution_clock :: now(( - start;

我想开始和结束的变量类型是错误的。什么是正确的类型?我想使用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;
}
}

timer.hpp 应该与某些主文件一起使用。
通过在我想测量的一些函数之前调用timer::initTime()并在功能之后调用timer::endTime(),我将获得计时结果(此处省略了持续时间的getter(。

此代码有两个问题:

static std::chrono::system_clock::time_point start, end;
/* ... */
void endTime(){
    end = std::chrono::high_resolution_clock::now() - start;
}

您将end声明为时间点,但是在分配操作员的右侧,您要减去两个时间点(now()start(,然后分配给end

从逻辑上讲,如果您减去两个时间点,则不会获得新的时间点。例如,如果我想减去"今天的08:15:00" - "今天的08:05:00",将结果描述为" 00:10:00今天"是没有意义的。相反,C Chrono库具有duration类模板。它旨在表示时间长度(例如两个时间点之间的差异(。

请参阅operator - Overload编号4:http://en.cppreference.com/w/cpp/chrono/time_point/operator_arith2

我建议观看@howard Hinnant链接到上面的教程视频... Hinnant先生参与了开发std::chronoboost::chrono库。

电位 second 问题是start具有类型std::chrono::system_clock::time_point,它可能是与std::chrono::high_resolution_clock::now()返回的类型不同的类型(不同的时钟((具有std::chrono::high_resolution_clock::time_point类型(。