如果仔细看一下与std::chrono::high_resolution_clock
相关的C ++标准,您会发现它包含一个成员类型std::chrono::high_resolution_clock
,它等效于std::chrono::high_resolution_clock::time_point
。
我的初始代码是
using n_time = std::chrono::high_resolution_clock;
n_time::time_point c_time = n_time::now();
n_time::time_point start = n_time::now();
auto gyro::duration(){
return std::chrono::duration_cast<std::chrono::milliseconds>(c_time-start).count();
}
但是后来我意识到我想从now()
的起始参数中找到毫秒,因此我不确定我的初始代码是否能给我。所以我尝试过
auto timeSince(n_time::time_point start){
n_time now = n_time::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count();
}
您是如何找到start
之后的毫秒数的?我听说有一个叫做time_since_epoch()
的函数,我不确定是否可以使用它呢?
此时钟用于我要编写的特定机器人功能,因此我需要确保该时钟不会引起转换错误:
void straight(int distance, int speed){
int time = (distance / speed) * 1000; // milliseconds
while(timeSince() < time){
// code
duration()
函数在我的函数中没有给出任何错误,但是timeSince()
给了我转换错误,例如
error: conversion from 'int' to non-scalar type 'std::chrono::_V2::system_clock::time_point {aka std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long long int, std::ratio<1ll, 1000000000ll> > >}
我听说有一个名为time_since_epoch()的函数,但不确定是否可以使用它,] [>
有一个事实上的(非官方的)标准,std :: chrono :: system_clock :: time_point具有与Unix时间一致的纪元。定义为自1970年1月1日星期四00:00:00协调世界时(UTC)起经过的时间,不计算counting秒。
您看到的错误是由此行生成的
n_time now = n_time::now();
应该是
n_time::time_point now = n_time::now();
// ^^^^^^^^^^^^
给出using n_time = std::chrono::high_resolution_clock;
如果仔细看一下与std::chrono::high_resolution_clock
相关的C ++标准,您会发现它包含一个成员类型std::chrono::high_resolution_clock
,它等效于std::chrono::high_resolution_clock::time_point
。
除了上述成员类型之外,std::chrono::time_point<std::chrono::high_resolution_clock>
包含成员函数std::chrono::high_resolution_clock
,该函数返回now
,即std::chrono::time_point<std::chrono::high_resolution_clock>
,代表时钟的当前值。
在您的职务上,您有
std::chrono::high_resolution_clock::time_point
即您正在尝试将
n_time now = n_time::now();
分配给听起来不太清晰的std::chrono::high_resolution_clock::time_point
类型的变量,对吗?因此,您应该具有std::chrono::high_resolution_clock
这里是完整的代码:
n_time::time_point now = n_time::now();
结果以毫秒为单位:
#include <chrono> #include <iostream> using n_time = std::chrono::high_resolution_clock; auto timeSince(n_time::time_point start) { n_time::time_point now = n_time::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count(); } int main() { auto now = n_time::now() - std::chrono::seconds{3600}; std::cout << timeSince(now) << std::endl; return 0; }
UPDATE
这里是如何在您的情况下使用上述工作示例的方式:
3600000
如果仔细看一下与std::chrono::high_resolution_clock
相关的C ++标准,您会发现它包含一个成员类型std::chrono::high_resolution_clock
,它等效于std::chrono::high_resolution_clock::time_point
。