std::chrono:: duration_cast
|
ヘッダーで定義
<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
のdurationに変換します。
この関数は、オーバーロード解決に参加するのは
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つ以上のパラメータが 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(); // floating-point duration: no duration_cast needed const std::chrono::duration<double, std::milli> fp_ms = t2 - t1; // integral duration: requires duration_cast const auto int_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); // converting integral duration to integral duration of // shorter divisible time unit: no duration_cast needed 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)
|
時間間隔
(クラステンプレート) |
|
(C++11)
|
同じクロック上の異なるdurationを持つ別のtime_pointに変換する
(関数テンプレート) |
|
(C++17)
|
durationを別のdurationに変換し、切り捨てる
(関数テンプレート) |
|
(C++17)
|
durationを別のdurationに変換し、切り上げる
(関数テンプレート) |
|
(C++17)
|
durationを別のdurationに変換し、最も近い値に丸める(同値の場合は偶数方向)
(関数テンプレート) |