Namespaces
Variants
Views
Actions

Date and time utilities

From cppreference.com
< cpp
Revision as of 17:00, 2 November 2012 by P12bot (Talk | contribs)

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)

Contents

chrono library

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

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.

Template:cpp/chrono/dcl list duration
Defined in header <chrono>
Defined in namespace std::chrono

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:

Template:cpp/chrono/dcl list system clockTemplate:cpp/chrono/dcl list steady clockTemplate:cpp/chrono/dcl list high resolution clock
Defined in header <chrono>
Defined in namespace std::chrono

Time point

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

Template:cpp/chrono/dcl list time point
Defined in header <chrono>
Defined in namespace std::chrono

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.

Example

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

#include <iostream>
#include <chrono>
#include <ctime>
 
int fibonacci(int n)
{
    if (n < 3) return 1;
    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();
    int result = fibonacci(42);
    end = std::chrono::system_clock::now();
 
    int elapsed_seconds = std::chrono::duration_cast<std::chrono::seconds>
                             (end-start).count();
    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 << "s\n";
}

Possible output:

finished computation at Sat Jun 16 20:42:57 2012
elapsed time: 3s