C++ includes support for two types of time manipulation:
The chrono
library defines several main types as well as utility functions and common typedefs:
A clock consists of a starting point (or epoch) and a tick rate. For example, a clock may have an epoch of January 1, 1970 and tick every second. C++ defines several clock types:
[edit] Time pointA time point is a duration of time that has passed since the epoch of a specific clock.
[edit] DurationA duration consists of a span of time, defined as some number of ticks of some time unit. For example, "42 seconds" could be represented by a duration consisting of 42 ticks of a 1-second time unit.
[edit] Time of day (since C++20)hh_mm_ss
splits a duration representing time elapsed since midnight into hours, minutes, seconds, and fractional seconds, as applicable. It is primarily a formatting tool.
chrono
object from a stream
Also provided are the C-style date and time functions, such as std::time_t, std::difftime, and CLOCKS_PER_SEC.
[edit] Example#include <chrono> #include <iostream> long Fibonacci(unsigned n) { return n < 2 ? n : Fibonacci(n - 1) + Fibonacci(n - 2); } int main() { // Measures and displays an execution time of a function call. const auto start{std::chrono::steady_clock::now()}; const auto fb{Fibonacci(42)}; const auto finish{std::chrono::steady_clock::now()}; const std::chrono::duration<double> elapsed_seconds{finish - start}; std::cout << "Fibonacci(42): " << fb << "\nElapsed time: "; // std::cout << elapsed_seconds.count() << "s\n"; // Before C++20 std::cout << elapsed_seconds << '\n'; // C++20's chrono::duration operator<< // Prints UTC and local time. const auto tp_utc{std::chrono::system_clock::now()}; std::cout << "Current time 'UTC' is: " << tp_utc << "\n" "Current time 'Local' is: " << std::chrono::current_zone()->to_local(tp_utc) << '\n'; }
Possible output:
Fibonacci(42): 267914296 Elapsed time: 0.728532s Current time 'UTC' is: 2025-02-10 06:22:39.420666960 Current time 'Local' is: 2025-02-10 09:22:39.420666960
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4