std::chrono::round(std::chrono::duration)
来自cppreference.com
| 在标头 <chrono> 定义
|
||
| |
(C++17 起) | |
返回 ToDuration 可以表示的最接近 d 的 {{tt|t} 。若有两个这样的值,则返回偶数值(即使得 t % 2 == 0 的值 t)。
除非 ToDuration 是 std::chrono::duration 的特化且 std::chrono::treat_as_floating_point_v<typename ToDuration::rep> 为 false,否则函数不参与重载决议。
参数
| d | - | 要转换的时长 |
返回值
取整到 ToDuration 类型的最接近 d 时长,两值正中的情况取到偶数。
可能的实现
namespace detail
{
template<class> inline constexpr bool is_duration_v = false;
template<class Rep, class Period> inline constexpr bool is_duration_v<
std::chrono::duration<Rep, Period>> = true;
}
template<class To, class Rep, class Period,
class = std::enable_if_t<detail::is_duration_v<To> &&
!std::chrono::treat_as_floating_point_v<typename To::rep>>>
constexpr To round(const std::chrono::duration<Rep, Period>& d)
{
To t0 = std::chrono::floor<To>(d);
To t1 = t0 + To{1};
auto diff0 = d - t0;
auto diff1 = t1 - d;
if (diff0 == diff1)
{
if (t0.count() & 1)
return t1;
return t0;
}
else if (diff0 < diff1)
return t0;
return t1;
}
|
示例
Run this code
#include <iostream>
#include <iomanip>
#include <chrono>
int main()
{
using namespace std::chrono_literals;
using Sec = std::chrono::seconds;
for (std::cout << "Duration\tFloor\tRound\tCeil\n"
"(ms)\t\t(sec)\t(sec)\t(sec)\n";
auto const d: {
+4999ms, +5000ms, +5001ms, +5499ms, +5500ms, +5999ms,
-4999ms, -5000ms, -5001ms, -5499ms, -5500ms, -5999ms, }) {
std::cout << std::showpos << d.count() << "\t\t"
<< std::chrono::floor<Sec>(d).count() << '\t'
<< std::chrono::round<Sec>(d).count() << '\t'
<< std::chrono::ceil <Sec>(d).count() << '\n';
}
}
输出:
Duration Floor Round Ceil
(ms) (sec) (sec) (sec)
+4999 +4 +5 +5
+5000 +5 +5 +5
+5001 +5 +5 +6
+5499 +5 +5 +6
+5500 +5 +6 +6
+5999 +5 +6 +6
-4999 -5 -5 -4
-5000 -5 -5 -5
-5001 -6 -5 -5
-5499 -6 -5 -5
-5500 -6 -6 -5
-5999 -6 -6 -5
参阅
(C++11) |
转换时长到另一个拥有不同计次间隔的时长 (函数模板) |
(C++17) |
以向下取整的方式,将一个时长转换为另一个时长 (函数模板) |
(C++17) |
以向上取整的方式,将一个时长转换为另一个时长 (函数模板) |
| 转换 time_point 到另一个,就近取整,偶数优先 (函数模板) | |
(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11)(C++11) |
最接近整数,中间情况下向远离零舍入 (函数) |