c++ - 使用 chrono 将 time_point 转换为特定持续时间

标签 c++ c++11

/*definition of start and end
std::chrono::time_point<std::chrono::system_clock> start;
std::chrono::time_point<std::chrono::system_clock> _end;
*/

std::chrono::time_point<std::chrono::system_clock> someclass::spf()
{
    _end = std::chrono::system_clock::now();
    std::chrono::time_point<std::chrono::system_clock> time(_end-start);
    start = std::chrono::system_clock::now();
    return time;
}
unsigned int someclass::secs()
{
    return std::chrono::duration_cast<std::chrono::seconds>(spf()).count();
}

编译器给我调用 duration_cast 的错误。确切错误:

error: no matching function for call to ‘duration_cast(std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1l, 1000000000l> > >)’

最佳答案

时间点 ( std::chrono::time_point<...> ) 不是持续时间 ( std::chrono::duration<...> ,例如 std::chrono::seconds 是一个 typedef)。

它们是不同的类型。

您正在尝试施放持续时间,但 spf 返回一个 time_point。持续时间是 2 个 time_point 之间的时间。 因此,要从一个 time_point 获取持续时间,您需要另一个 time_point 并获取这些 time_point 之间的持续时间。

所以这里你的错误是在 spf 中返回一个 time_point 而不是一个持续时间,并且这一行是错误的:

std::chrono::time_point<std::chrono::system_clock> time(_end-start);

您显然想要一个持续时间,但要构建一个 time_point。改为这样做:

const auto time_since_start = _end - start;
//...
return time_since_start; // you might need a duration cast here depending on what spf() will return.

所以 spf() 的返回类型必须是一个持续时间,比如秒或毫秒或任何你想要的。

关于c++ - 使用 chrono 将 time_point 转换为特定持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21615970/

相关文章:

c++ - 为什么 list<unique_ptr> 中的 unique_ptr 的 std::move() 没有真正 move 它?

c++ - 使用 RecursiveASTVisitor 访问 Clang AST 时确定 Stmt 的父函数节点

c++ - 使用 C++11 原子编写(旋转)线程屏障

c++ - 如何显式调用 std 迭代器的析构函数?

c++ - 在自定义 const native C++ 容器类上支持 "for each"

c++ - 试图在 C++ 中创建一个具有 2 个对象作为变量的类。链接和非静态错误

c++ - 修复已添加构造函数的结构的初始化

c++ - 使用 Win32 线程模型时,MinGW-w64 是否支持开箱即用的 std::thread?

c++ - 结构的隐式列表初始化构造函数

c++ - 为什么他们有系统字符串和标准字符串