File: duration-division.rst

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (36 lines) | stat: -rw-r--r-- 1,444 bytes parent folder | download | duplicates (25)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
.. title:: clang-tidy - abseil-duration-division

abseil-duration-division
========================

``absl::Duration`` arithmetic works like it does with integers. That means that
division of two ``absl::Duration`` objects returns an ``int64`` with any fractional
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``.

For example:

.. code-block:: c++

 absl::Duration d = absl::Seconds(3.5);
 int64 sec1 = d / absl::Seconds(1);     // Truncates toward 0.
 int64 sec2 = absl::ToInt64Seconds(d);  // Equivalent to division.
 assert(sec1 == 3 && sec2 == 3);

 double dsec = d / absl::Seconds(1);  // WRONG: Still truncates toward 0.
 assert(dsec == 3.0);

If you want floating-point division, you should use either the
``absl::FDivDuration()`` function, or one of the unit conversion functions such
as ``absl::ToDoubleSeconds()``. For example:

.. code-block:: c++

 absl::Duration d = absl::Seconds(3.5);
 double dsec1 = absl::FDivDuration(d, absl::Seconds(1));  // GOOD: No truncation.
 double dsec2 = absl::ToDoubleSeconds(d);                 // GOOD: No truncation.
 assert(dsec1 == 3.5 && dsec2 == 3.5);


This check looks for uses of ``absl::Duration`` division that is done in a
floating-point context, and recommends the use of a function that returns a
floating-point value.