@@ -928,10 +928,12 @@ using years = duration<int, ratio_multiply<ratio<146097, 400>, days::period>>;
928928using months = duration<int , ratio_divide<years::period, ratio<12 >>>;
929929```
930930
931+ 如果没有指明 ` duration ` 的第二个非类型模板参数,那么代表默认 ` std::ratio<1> ` ,比如 ` seconds ` 也就是一秒。
932+
931933如上,是 MSVC STL 定义的,看似有一些没有使用 ` ratio ` 作为第二个参数,其实也还是别名罢了,[ 见] ( https://github.com/microsoft/STL/blob/daeb0a6/stl/inc/ratio#L262-L277 ) :
932934
933935``` cpp
934- using milli = ratio<1 , 1000 >;
936+ using milli = ratio<1 , 1000 >; // 千分之一秒,也就是一毫秒了
935937```
936938
937939并且为了方便使用,在 C++14 标准库增加了时间字面量,存在于 ` std::chrono_literals ` 命名空间中,让我们得以简单的使用:
@@ -955,7 +957,30 @@ std::chrono::seconds s = std::chrono::duration_cast<std::chrono::seconds>(ms);
955957std::cout << s.count() << '\n';
956958```
957959
958- 这里的结果是截断的,而不会进行所谓的四舍五入,最终的值是 ` 3 ` 。
960+ 这里的结果是** 截断** 的,而不会进行所谓的四舍五入,` 3999 ` 毫秒,也就是 ` 3.999 ` 秒最终的值是 ` 3 ` 。
961+
962+ > 很多时候这并不是我们想要的,比如我们想要的其实是输出 `3.999 ` 秒,而不是 `3 ` 秒 或者 `3999 ` 毫秒。
963+ >
964+ > seconds 是 `duration<long long >` 这意味着它无法接受浮点数,我们直接改成 `duration<double >` 即可:
965+ >
966+ > ```cpp
967+ > std::chrono::duration<double > s = std::chrono::duration_cast<std::chrono::duration<double >>(ms);
968+ > ```
969+ >
970+ > 当然了,这样写很冗余,并且这种形式的转换是可以直接隐式的,也就是其实我们可以直接:
971+ >
972+ > ```cpp
973+ > std::chrono::duration<double > s = ms;
974+ > ```
975+ >
976+ > 无需使用 `duration_cast`,可以直接隐式转换。
977+ >
978+ > 另外我们用的 `duration` 都是省略了 `ratio` 的,其实默认类型就是 `ratio<1 >`,代表一秒。参见源码[声明](https:// github.com/microsoft/STL/blob/0be5257/stl/inc/__msvc_chrono.hpp#L80-L81):
979+ >
980+ > ```cpp
981+ > _EXPORT_STD template <class _Rep , class _ Period = ratio<1>>
982+ > class duration ;
983+ > ```
959984
960985时间库支持四则运算,可以对两个时间段进行加减乘除。时间段对象可以通过 [`count()`](https:// zh.cppreference.com/w/cpp/chrono/duration/count) 成员函数获得计次数。例如 `std::chrono::milliseconds{123}.count()` 的结果就是 123。
961986
@@ -1207,7 +1232,7 @@ async_progress_bar::async_progress_bar(QWidget *parent)
12071232
12081233### 跨平台兼容性
12091234
1210- C++11 的 `std::this_thread::get_id()` 返回的内部类型没办法直接转换为 `unsigned int`,我们就直接使用了 win32 的 API *`_Thrd_id()`* 了。如果您是 Linux 之类的环境,使用 [POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/) 接口 [*`pthread_self()`*](https://pubs.opengroup.org/onlinepubs/009696699/functions/pthread_self.html)。
1235+ C++11 的 `std::this_thread::get_id()` 返回的内部类 [`std::thread::id`](https://zh.cppreference.com/w/cpp/thread/thread/id) 没办法直接转换为 `unsigned int`,我们就直接使用了 win32 的 API *`_Thrd_id()`* 了。如果您是 Linux 之类的环境,使用 [POSIX](https://pubs.opengroup.org/onlinepubs/9699919799/) 接口 [*`pthread_self()`*](https://pubs.opengroup.org/onlinepubs/009696699/functions/pthread_self.html)。
12111236
12121237### 实践建议
12131238
0 commit comments