首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::chrono::duration_cast

template <class ToDuration, class Rep, class Period> constexpr ToDuration duration_cast(const duration<Rep,Period>& d);

?

(since C++11)

转换std::chrono::duration到不同类型的持续时间。ToDuration...

不使用隐式转换。如果在编译时已知有一个或多个参数,则在可能的情况下避免乘法和除法。1.计算以可用的最宽类型进行,并转换为static_cast,只在完成后才输入结果类型。

参数

d

-

duration to convert

返回值

d转换为类型的持续时间ToDuration...

注记

该函数不参与重载解析,除非ToDurationstd::chrono::duration...

在浮点持续时间之间或整数持续时间之间进行转换,其中源周期完全可以被目标周期%28(例如)整除。小时到分钟%29可以执行隐式,不duration_cast是必要的。

从浮点持续时间到整数持续时间的转换为服从未定义的行为当浮点值为NaN、无穷大或太大时,目标%27s整数类型无法表示。

此示例度量函数的执行时间。

二次

代码语言:javascript
复制
#include <iostream>
#include <chrono>
#include <ratio>
#include <thread>
 
void f()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    auto t1 = std::chrono::high_resolution_clock::now();
    f();
    auto t2 = std::chrono::high_resolution_clock::now();
 
    // integral duration: requires duration_cast
    auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
 
    // fractional duration: no duration_cast needed
    std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
 
    std::cout << "f() took " << fp_ms.count() << " ms, "
              << "or " << int_ms.count() << " whole milliseconds\n";
}

二次

可能的产出:

二次

代码语言:javascript
复制
f() took 1000.23 ms, or 1000 whole milliseconds

二次

另见

time_point_cast

converts a time point to another time point on the same clock, with a different duration (function template)

floor(std::chrono::duration) (C++17)

converts a duration to another, rounding down (function template)

ceil(std::chrono::duration) (C++17)

converts a duration to another, rounding up (function template)

round(std::chrono::duration) (C++17)

converts a duration to another, rounding to nearest, ties to even (function template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com