Date and time utilities - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# Date and time utilities

From cppreference.com
< cpp

C++ includes support for two types of time manipulation:

- The `chrono` library, a flexible collection of types that track time with varying degrees of precision (e.g. std::chrono::time_point).
- C-style date and time library (e.g. std::time)

### [edit] `chrono` library

The `chrono` library defines three main types (durations, clocks, and time points) as well as utility functions and common typedefs.

#### [edit] Duration

A 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.

Defined in header `<chrono>`
Defined in namespace `std::chrono`
duration (C++11) | a time interval (class template) [edit]

#### [edit] Clocks

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 three clock types:

Defined in header `<chrono>`
Defined in namespace `std::chrono`
system_clock (C++11) | wall clock time from the system-wide realtime clock (class) [edit]
steady_clock (C++11) | monotonic clock that will never be adjusted (class) [edit]
high_resolution_clock (C++11) | the clock with the shortest tick period available (class) [edit]

#### [edit] Time point

A time point is a duration of time that has passed since the epoch of specific clock.

Defined in header `<chrono>`
Defined in namespace `std::chrono`
time_point (C++11) | a point in time (class template) [edit]

### [edit] C-style date and time library

Also provided are the C-style date and time functions, such as std::time_t, std::difftime, and CLOCKS_PER_SEC.

### [edit] Example

This example displays information about the execution time of a function call:

Run this code

    #include <iostream>
    #include <chrono>
    #include <ctime>

    long fibonacci(unsigned n)
    {
        if (n < 2) return n;
        return fibonacci(n-1) + fibonacci(n-2);
    }

    int main()
    {
        std::chrono::time_point<std::chrono::system_clock> start, end;
        start = std::chrono::system_clock::now();
        std::cout << "f(42) = " << fibonacci(42) << '\n';
        end = std::chrono::system_clock::now();

        std::chrono::duration<double> elapsed_seconds = end-start;
        std::time_t end_time = std::chrono::system_clock::to_time_t(end);

        std::cout << "finished computation at " << std::ctime(&end_time)
                  << "elapsed time: " << elapsed_seconds.count() << "s\n";
    }

Possible output:

    f(42) = 267914296
    finished computation at Mon Jul 29 08:41:09 2013
    elapsed time: 0.670427s

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/chrono&oldid=72479"