CKTIS / C++
std::chrono::duration: a count of ticks with a period
std::chrono::duration<Rep, Period> represents a time interval as a count of ticks whose period is a constant fraction of a second.
Version: C++23
Syntax
template<class Rep, class Period = std::ratio<1>>
class duration {
public:
constexpr Rep count() const;
};
using nanoseconds = duration</* signed integer type */, std::nano>;
using milliseconds = duration</* signed integer type */, std::milli>;
using seconds = duration</* signed integer type */>;
using minutes = duration</* signed integer type */, std::ratio<60>>;
using days = duration</* signed integer type */, std::ratio<86400>>;std::chrono::duration<Rep, Period> from <chrono> stores a Rep value, while Period is a positive std::ratio defining one tick in seconds. Aliases such as seconds, milliseconds, and nanoseconds differ in period and often representation. count() returns the raw tick count, not seconds.
std::chrono::nanoseconds, std::chrono::milliseconds, std::chrono::seconds, std::chrono::minutes, and std::chrono::days are standard duration aliases with periods of 10^-9 s, 10^-3 s, 1 s, 60 s, and 86400 s respectively. std::chrono::duration::count returns the representation value in that object’s period; the number alone carries no unit information.
Duration arithmetic selects a common representation and period. An implicit conversion between integral representations is allowed only when no fractional part is lost. When the destination Rep is integral, duration_cast truncates toward zero; floor, ceil, and round explicitly select other rules. With a floating-point destination Rep, the result follows that representation’s normal rules.
Precision and range depend on Rep. Overflow and division by zero follow that representation type’s rules; for an integral Rep, signed overflow and division by zero are undefined behavior. zero(), min(), and max() provide special values. Do not confuse an interval with time_point, which anchors it to a clock.
Examples
#include <chrono>
#include <iostream>
int main() {
const std::chrono::milliseconds elapsed{1500};
const auto wholeSeconds = std::chrono::duration_cast<std::chrono::seconds>(elapsed);
std::cout << elapsed.count() << ' ' << wholeSeconds.count() << '\n';
}
Result
1500 1
std::chrono::duration → 1500 1