| 1 |
.. title:: clang-tidy - abseil-duration-division |
| 2 |
|
| 3 |
abseil-duration-division |
| 4 |
======================== |
| 5 |
|
| 6 |
``absl::Duration`` arithmetic works like it does with integers. That means that |
| 7 |
division of two ``absl::Duration`` objects returns an ``int64`` with any fractional |
| 8 |
component truncated toward 0. See `this link <https://github.com/abseil/abseil-cpp/blob/29ff6d4860070bf8fcbd39c8805d0c32d56628a3/absl/time/time.h#L137>`_ for more information on arithmetic with ``absl::Duration``. |
| 9 |
|
| 10 |
For example: |
| 11 |
|
| 12 |
.. code-block:: c++ |
| 13 |
|
| 14 |
absl::Duration d = absl::Seconds(3.5); |
| 15 |
int64 sec1 = d / absl::Seconds(1); // Truncates toward 0. |
| 16 |
int64 sec2 = absl::ToInt64Seconds(d); // Equivalent to division. |
| 17 |
assert(sec1 == 3 && sec2 == 3); |
| 18 |
|
| 19 |
double dsec = d / absl::Seconds(1); // WRONG: Still truncates toward 0. |
| 20 |
assert(dsec == 3.0); |
| 21 |
|
| 22 |
If you want floating-point division, you should use either the |
| 23 |
``absl::FDivDuration()`` function, or one of the unit conversion functions such |
| 24 |
as ``absl::ToDoubleSeconds()``. For example: |
| 25 |
|
| 26 |
.. code-block:: c++ |
| 27 |
|
| 28 |
absl::Duration d = absl::Seconds(3.5); |
| 29 |
double dsec1 = absl::FDivDuration(d, absl::Seconds(1)); // GOOD: No truncation. |
| 30 |
double dsec2 = absl::ToDoubleSeconds(d); // GOOD: No truncation. |
| 31 |
assert(dsec1 == 3.5 && dsec2 == 3.5); |
| 32 |
|
| 33 |
|
| 34 |
This check looks for uses of ``absl::Duration`` division that is done in a |
| 35 |
floating-point context, and recommends the use of a function that returns a |
| 36 |
floating-point value. |