Namespaces
Variants

std::chrono:: duration_cast

From cppreference.net
定义于头文件 <chrono>
template < class ToDuration, class Rep, class Period >
constexpr ToDuration duration_cast ( const std:: chrono :: duration < Rep, Period > & d ) ;
(C++11 起)

std::chrono::duration 转换为不同类型 ToDuration 的时长。

该函数仅在 ToDuration std::chrono::duration 的特化时才参与重载决议。

  • ToRep typename ToDuration :: rep
  • ToPeriod typename ToDuration :: period
  • CF std:: ratio_divide < Period, ToPeriod >
  • CR std:: common_type < Rep, ToRep, std:: intmax_t > :: type
  • cr_count static_cast < CR > ( d. count ( ) )
  • cr_num static_cast < CR > ( CF :: num ) ,以及
  • cr_den static_cast < CR > ( CF :: den )

结果为:

CF :: num
1 1
CF :: den 1 ToDuration ( static_cast < ToRep >
( d. count ( ) ) )
ToDuration ( static_cast < ToRep >
( cr_count * cr_num ) )
1 ToDuration ( static_cast < ToRep >
( cr_count / cr_den ) )
ToDuration ( static_cast < ToRep >
( cr_count * cr_num / cr_den ) )

目录

参数

d - 待转换的时间长度

返回值

d 转换为 ToDuration 类型的时长。

注释

不使用隐式转换。在编译时已知一个或多个参数为 1 的情况下,尽可能避免乘除运算。计算过程始终使用最宽的数据类型执行,仅在最终完成时通过 static_cast 方式转换到结果类型。

当源周期可被目标周期整除(例如从小时转换为分钟)时,在整数时长类型之间进行转换,或在浮点时长类型之间进行转换时,可通过普通类型转换或通过 std::chrono::duration 构造函数 隐式实现,无需使用 duration_cast

从浮点型时长转换为整型时长时,若浮点值为NaN、无穷大或超出目标整型表示范围,将 导致未定义行为 。其他情况下,转换为整型时长会像任何 static_cast 到整型那样发生截断。

示例

此示例用于测量函数的执行时间。

#include <chrono>
#include <iostream>
#include <ratio>
#include <thread>
void f()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main()
{
    const auto t1 = std::chrono::high_resolution_clock::now();
    f();
    const auto t2 = std::chrono::high_resolution_clock::now();
    // 浮点型时长:无需 duration_cast
    const std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
    // 整型时长:需要 duration_cast
    const auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
    // 将整型时长转换为可整除的更短时间单位的整型时长:无需 duration_cast
    const std::chrono::duration<long, std::micro> int_usec = int_ms;
    std::cout << "f() took " << fp_ms << ", or "
              << int_ms << " (whole milliseconds), or "
              << int_usec << " (whole microseconds)\n";
}

可能的输出:

f() took 1000.14ms, or 1000ms (whole milliseconds), or 1000000us (whole microseconds)

参见

(C++11)
时间间隔
(类模板)
将时间点转换为同一时钟下具有不同持续时间的时间点
(函数模板)
将持续时间转换为另一种持续时间,向下取整
(函数模板)
将持续时间转换为另一种持续时间,向上取整
(函数模板)
将持续时间转换为另一种持续时间,四舍五入到最接近的值,平局时取偶
(函数模板)