[/
 / Copyright (c) 2008 Howard Hinnant
 / Copyright (c) 2006, 2008 Beman Dawes
 / Copyright (c) 2009-20010 Vicente J. Botet Escriba
 /
 / Distributed under the Boost Software License, Version 1.0. (See accompanying
 / file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
 /]

[library Boost.Chrono
    [quickbook 1.5]
    [version 1.1.0]
    [authors [Hinnant, Howard]]
    [authors [Dawes, Beman]]
    [authors [Botet Escriba, Vicente J.]]
    [copyright 2008 Howard Hinnant]
    [copyright 2006, 2008 Beman Dawes]
    [copyright 2009-2011 Vicente J. Botet Escriba]
    [category utilities system]
    [id chrono]
    [dirname chrono]
    [purpose 
        Useful time utilities.
    ]
    [license
        Distributed under the Boost Software License, Version 1.0.
        (See accompanying file LICENSE_1_0.txt or copy at
        [@http://www.boost.org/LICENSE_1_0.txt])
    ]
]

[/==================]
[def __Boost_Chrono__ [*Boost.Chrono]]

[def __see_bellow__ ['see bellow]]

[/===============================================]
[def __inherit [*Inherits:]]
[def __std_ref [*C++ Standard Reference:]]
[def __header [*Header:]]
[def __compat [*Compiler Compatibility:]]
[def __examples [*Examples:]]
[def __example [*Example:]]
[def __type [*type:]]
[def __returns [*Returns:]]
[def __throws [*Throws:]]
[def __remarks [*Remarks:]]
[def __effects [*Effects:]]
[def __post_conditions [*PostConditions:]]
[def __pre_conditions [*PreConditions:]]
[def __requires [*Requires:]]

[template mu[]'''&#x3BC;'''] [/ µ Greek small letter mu]
[template plusminus[]'''&#x00B1;'''] [/  ? plus or minus sign]


[/===============================================]
[def __common_type `common_type`]


[/===============================================]
[def __ratio `ratio`]

[def __ratio_add `ratio_add`]
[def __ratio_subtract `ratio_subtract`]
[def __ratio_multiply `ratio_multiply`]
[def __ratio_divide `ratio_divide`]


[def __ratio_equal `ratio_equal`]
[def __ratio_not_equal `ratio_not_equal`]
[def __ratio_less `ratio_less`]
[def __ratio_less_equal `ratio_less_equal`]
[def __ratio_greater `ratio_greater`]
[def __ratio_greater_equal `ratio_greater_equal`]


[def __atto `atto`]
[def __femto `femto`]
[def __pico `pico`]
[def __nano `nano`]
[def __micro `micro`]
[def __milli `milli`]
[def __centi `centi`]
[def __deci `deci`]
[def __deca `deca`]
[def __hecto `hecto`]
[def __kilo `kilo`]
[def __mega `mega`]
[def __giga `giga`]
[def __tera `tera`]
[def __peta `peta`]
[def __exa `exa`]


[/==================]


[template chrono_conf[link_text] [link chrono.reference.cpp0x.chrono_chrono_hpp.conf [link_text]]]

[def __BOOST_CHRONO_HEADER_ONLY [link chrono.reference.cpp0x.chrono_hpp.conf.header_only `BOOST_CHRONO_HEADER_ONLY`]]
[def __BOOST_SYSTEM_INLINED `BOOST_SYSTEM_INLINED`]

[def __BOOST_CHRONO_USES_STATIC_ASSERT [chrono_conf `BOOST_CHRONO_USES_STATIC_ASSERT`]]
[def __BOOST_CHRONO_USES_MPL_ASSERT [chrono_conf `BOOST_CHRONO_USES_MPL_ASSERT`]]
[def __BOOST_CHRONO_USES_ARRAY_ASSERT [chrono_conf `BOOST_CHRONO_USES_ARRAY_ASSERT`]]

[def __BOOST_CHRONO_HAS_CLOCK_STEADY [link chrono.reference.cpp0x.system_clocks_hpp.BOOST_CHRONO_HAS_CLOCK_STEADY `BOOST_CHRONO_HAS_CLOCK_STEADY`]]

[def __BOOST_CHRONO_HAS_THREAD_CLOCK [link chrono.reference.other_clocks.thread_clock_hpp.BOOST_CHRONO_HAS_THREAD_CLOCK `BOOST_CHRONO_HAS_THREAD_CLOCK`]]



[template clock_concept_link[link_text] [link chrono.reference.cpp0x.clock [link_text]]]
[def __clock_req [clock_concept_link `Clock`] requirements]
[def __Clock [clock_concept_link `Clock`]]
[def __Clock_s [clock_concept_link `Clock`'s]]

[def __duration [link chrono.reference.cpp0x.duration_hpp.duration `duration`]]
[def __durations [link chrono.reference.cpp0x.duration_hpp.duration `duration`]s]
[def __duration_s [link chrono.reference.cpp0x.duration_hpp.duration `duration`]'s]

[/==================]
[def __time_point [link chrono.reference.cpp0x.time_point_hpp.time_point `time_point`]]
[def __time_points [link chrono.reference.cpp0x.time_point_hpp.time_point `time_point`]s]
[def __time_point_s [link chrono.reference.cpp0x.time_point_hpp.time_point `time_point`]'s]

[/==================]
[def __system_clock [link chrono.reference.cpp0x.system_clocks_hpp.system_clock `system_clock`]]
[def __steady_clock [link chrono.reference.cpp0x.system_clocks_hpp.steady_clock `steady_clock`]]
[def __high_resolution_clock [link chrono.reference.cpp0x.system_clocks_hpp.high_resolution_clock `high_resolution_clock`]]

[/==================]

[def __process_real_cpu_clock [link chrono.reference.other_clocks.process_cpu_clocks_hpp.process_real_cpu_clock `process_real_cpu_clock`]]
[def __process_system_cpu_clock [link chrono.reference.other_clocks.process_cpu_clocks_hpp.process_system_cpu_clock `process_system_cpu_clock`]]
[def __process_user_cpu_clock [link chrono.reference.other_clocks.process_cpu_clocks_hpp.process_user_cpu_clock `process_user_cpu_clock`]]
[def __process_cpu_clock [link chrono.reference.other_clocks.process_cpu_clocks_hpp.process_cpu_clock `process_cpu_clock`]]
[def __thread_clock [link chrono.reference.other_clocks.thread_clock_hpp.thread_clock `thread_clock`]]

[/==================]
[def __duration_cast [link chrono.reference.cpp0x.duration_hpp.duration_cast `duration_cast`]]
[def __time_point_cast [link chrono.reference.cpp0x.time_point_hpp.time_point_cast `time_point_cast`]]


[def __nanoseconds [link chrono.reference.cpp0x.duration_hpp.duration_typedefs `nanoseconds`]]
[def __microseconds [link chrono.reference.cpp0x.duration_hpp.duration_typedefs `microseconds`]]
[def __milliseconds__ [link chrono.reference.cpp0x.duration_hpp.duration_typedefs `milliseconds`]]
[def __seconds [link chrono.reference.cpp0x.duration_hpp.duration_typedefs `seconds`]]
[def __minutes [link chrono.reference.cpp0x.duration_hpp.duration_typedefs `minutes`]]
[def __hours [link chrono.reference.cpp0x.duration_hpp.duration_typedefs `hours`]]

[def __common_type_spe [link chrono.reference.cpp0x.duration_hpp.common_type_spe `common_type`]]

[/==================]
[def __treat_as_floating_point [link chrono.reference.cpp0x.duration_hpp.traits.treat_as_floating_point `treat_as_floating_point`]]
[def __duration_values [link chrono.reference.cpp0x.duration_hpp.traits.duration_values `duration_values`]]
[def __zero [link chrono.reference.cpp0x.duration_hpp.traits.duration_values.zero `zero`]]
[def __max [link chrono.reference.cpp0x.duration_hpp.traits.duration_values.max `max`]]
[def __min [link chrono.reference.cpp0x.duration_hpp.traits.duration_values.min `min`]]



[/==================]

[def __duration_punct [link chrono.reference.io.chrono_io_hpp.duration_punct `duration_punct`]]


[/===============]
[section Overview]
[/===============]

[:["What is time, then? If nobody asks me, I know; if I have to explain it to someone who has asked me, I do not know."]]
[:[*['-- Augustine ]]]


[/====================================]
[heading How to Use This Documentation]
[/====================================]

This documentation makes use of the following naming and formatting conventions.

* Code is in `fixed width font` and is syntax-highlighted.
* Replaceable text that you will need to supply is in [~italics].
* Free functions are rendered in the code font followed by `()`, as in `free_function()`.
* If a name refers to a class template, it is specified like this:   `class_template<>`; that is, it is in code font and its name is followed by `<>`   to indicate that it is a class template.
* If a name refers to a function-like macro, it is specified like this: `MACRO()`;
  that is, it is uppercase in code font and its name is followed by `()` to   indicate that it is a function-like macro. Object-like macros appear without the   trailing `()`.
* Names that refer to /concepts/ in the generic programming sense are  specified in CamelCase.

[note In addition, notes such as this one specify non-essential information that provides additional background or rationale.]

Finally, you can mentally add the following to any code fragments in this document:

    // Include all of Chrono files
    #include <boost/chrono.hpp>

[/=================]
[section Motivation]
[/=================]

[heading Time]

We all deal with time every day of our lives. We've intuitively known it since birth. Thus we are all very familiar with it and believe it to be a simple matter. The modeling of time in computer programs should be similarly simple. The unfortunate truth is that this perceived simplicity is only skin deep. Fortunately, we do not need a terribly complicated solution to meet the bulk of our needs. However, overly simplistic solutions can be dangerous and inefficient, and won't adapt as the computer industry evolves.

__Boost_Chrono__ aims to implement the new time facilities in C++0x, as proposed in [@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm [*N2661 - A Foundation to Sleep On]].  That document provides background and motivation for key design decisions and is the source of a good deal of information in this documentation.

[/
__Boost_Chrono__ proposes a solution that is precision neutral, with a very simple end user interface which supports multiple clocks, multiple precisions (both coarser and finer than we will ever need), separate types for points in time and time durations, efficiency, and compile-time enforced safety.
]

[/
In addition to the clocks provided by the standard proposal, __Boost_Chrono__ provides specific process clocks and a thread clock.
]

[/
See [@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm [*N2661 - A Foundation to Sleep On]] which is very informative and provides motivation for key design decisions for __common_type, __ratio and `chrono`. This documentation contains a lot of extracts from this document.
]

[heading Wall clock versus system and user time]

To make the timing facilities of Boost.Chrono more generally useful, the library provides a number of clocks that are thin wrappers around the operating system's process time API, thereby allowing the extraction of wall clock time, user CPU time, and system CPU time of the process.  Wall clock time is the sum of CPU time and system CPU time. (On POSIX-like systems, this relies on `times()`.  On Windows, it relies on `GetProcessTimes()`.)

[/
It is also helpful if such timing information is broken down into real (wall clock) time, CPU time spent by the user, and CPU time spent by the operating system servicing user requests.
]

[/
3 concrete process clocks:

# __process_real_cpu_clock,
# __process_user_cpu_clock,
# __process_system_cpu_clock

providing a
]

[/__Boost_Chrono__ provides
thin wrappers around the operating system's process timer API. For POSIX-like systems, that's the times() function, while for Windows, it's the GetProcessTimes() function.
]

[/These clocks capture the specific time unitarily. __Boost_Chrono__ provides also a clock __process_cpu_clock that captures the three times at once.
]


[endsect]

[/==================]
[section Description]
[/==================]

The __Boost_Chrono__ library provides:

[heading Standard]

* A means to represent time durations: managed by the generic __duration class . Examples of time durations include days, __minutes, __seconds  and __nanoseconds, which can be represented with a fixed number of clock ticks per unit. All of these units of time duration are united with a generic interface by the __duration facility.
* A type for representing points in time: __time_point. A __time_point represents an epoch plus or minus a __duration. The library leaves epochs unspecified. A __time_point is associated with a /clock/.
* Several clocks, some of which may not be available on a particular platform: __system_clock, __steady_clock and __high_resolution_clock. A clock is a pairing of a __time_point and __duration, and a function which returns a __time_point representing ['now].

[heading Other clocks]

To make the timing facilities more generally useful, __Boost_Chrono__ provides a number of clocks that are thin wrappers around the operating system's time APIs, thereby allowing the extraction of wall clock time, user CPU time, system CPU time spent by the process,

* __process_real_cpu_clock, captures wall clock CPU time spent by the current process.
* __process_user_cpu_clock, captures user-CPU time spent by the current process.
* __process_system_cpu_clock, captures system-CPU time  spent by the current process.
* A tuple-like class __process_cpu_clock, that captures real, user-CPU, and system-CPU process times together.
* A __thread_clock thread steady clock giving the time spent by the current thread (when supported by a platform).


[/It is also helpful if such timing information is broken down into real (wall clock) time, CPU time spent by the user, and CPU time spent by the operating system servicing user requests. process clocks provide a thin wrapper around the operating system's process timer API. For POSIX-like systems, that's the times() function, while for Windows, it's the GetProcessTimes() function.
]

Lastly, __Boost_Chrono__ includes [@http://www.boost.org/libs/typeof typeof] registration for __duration and __time_point to permit using emulated auto with C++03 compilers.

[heading I/O]

It provides I/O for __duration and __time_point. It builds on `<boost/ratio/ratio_io.hpp>` to provide readable and flexible formatting and parsing for types in `<boost/chrono.hpp>`. The __duration unit names can be customized through a new facet: __duration_punct.


[heading Caveat Emptor]

The underlying clocks provided by operating systems are subject to many seemingly arbitrary policies and implementation irregularities. That's a polite way of saying they tend to be flakey, and each operating system or even each clock has its own cruel and unusual forms of flakiness. Don't bet the farm on their accuracy, unless you have become deeply familiar with exactly what the specific operating system is guaranteeing, which is often very little.


[endsect]

[endsect]


[/==============================]
[section:users_guide User's Guide]
[/==============================]

[/======================================]
[section:getting_started Getting Started]
[/======================================]

[/======================================]
[section:install Installing Chrono]
[/======================================]

[/=================================]
[heading Getting __Boost_Chrono__ ]
[/=================================]

__Boost_Chrono__ is in the latest Boost release in the folder `/boost/chrono`.  Documentation, tests and examples folder are at `boost/libs/chrono/`.

You can also access the latest (unstable?) state from the [@https://svn.boost.org/svn/boost-trunk Boost trunk] directories boost/chrono and libs/chrono. Just go to [@http://svn.boost.org/trac/boost/wiki/BoostSubversion here] and follow the instructions there for anonymous SVN access.


[/==========================================]
[heading Where to install Boost.Chrono? ]
[/==========================================]

The simple way is to decompress (or checkout from SVN) the files in your BOOST_ROOT directory.


[/=================================]
[heading Building Boost.Chrono ]
[/=================================]

__Boost_Chrono__ can be configured as a header-only library. When __BOOST_CHRONO_HEADER_ONLY is defined the Boost.Chrono is a header-only library. Otherwise is not a header only library and you need to compile it and build the library before use, for example using:

    bjam libs/chrono/build

[/===================]
[heading Requirements]
[/===================]

[caution __Boost_Chrono__ depends on some new traits in [*Boost.TypeTraits] which have been added on Boost 1.45.]

In particular, __Boost_Chrono__ depends on:

[variablelist
[
    [[@http://www.boost.org/libs/config [*Boost.Config]]] [for configuration purposes, ...]
]
[
    [[@http://www.boost.org/libs/exception [*Boost.Exception]]] [for throw_exception, ...]
]
[
    [[@http://www.boost.org/libs/integer [*Boost.Integer]]] [for cstdint conformance, ...]
]
[
    [[@http://www.boost.org/libs/mpl [*Boost.MPL]]] [for MPL Assert and bool, logical ...]
]
[
    [[@http://www.boost.org/libs/operators [*Boost.Operators]]] [for operators, ...]
]
[
    [[@http://www.boost.org/libs/ratio [*Boost.Ratio]]] [for ratio, milli, micro, ...]
]
[
    [[@http://www.boost.org/libs/system [*Boost.System]]] [for error_code, ...]
]
[
    [[@http://www.boost.org/libs/type_traits [*Boost.TypeTraits]]] [for is_base, is_convertible, common_type, ...]
]
[
    [[@http://www.boost.org/libs/utility [*Boost.Utility/EnableIf]]] [for enable_if, ...]
]
]


[/=========================================================]
[heading Building an Executable that Uses Boost.Chrono ]
[/=========================================================]

In addition to link with the __Boost_Chrono__ library you need also to link with the [*Boost.System] library.
Once [*Boost.System] will be configurable to be a header only using __BOOST_SYSTEM_INLINED you will no need to link with it.


[/=========================]
[heading Exception safety ]
[/=========================]

All functions in the library are exception-neutral and provide strong guarantee of exception safety as long as the underlying parameters provide it.


[/=====================]
[heading Thread safety ]
[/=====================]

All functions in the library are thread-unsafe except when noted explicitly.

As Boost.Chrono doesn't use mutable global variables the thread-safety analysis is limited to the access to each instance variable. It is not thread safe to use a function that modifies the access to a user variable if another can be reading or writing it.


[/========================]
[heading Tested compilers ]
[/========================]

The implementation will eventually work with most C++03 conforming compilers.
Current version has been tested on:

Windows with

* MSVC 10.0

Cygwin 1.5 with

* GCC 3.4.4

Cygwin 1.7 with

* GCC 4.3.4

MinGW with

* GCC 4.4.0
* GCC 4.5.0
* GCC 4.5.0 -std=c++0x
* GCC 4.6.0
* GCC 4.6.0 -std=c++0x

Ubuntu 10.10

* GCC 4.4.5
* GCC 4.4.5 -std=c++0x
* GCC 4.5.1
* GCC 4.5.1 -std=c++0x
* clang 2.8

Initial versions were tested on:

MacOS with GCC 4.2.4 (Some test are needed for the specific Mac files).

Ubuntu Linux with GCC 4.2.4

[note Please let us know how this works on other platforms/compilers.]

[note Please send any questions, comments and bug reports to boost <at> lists <dot> boost <dot> org.]

[endsect]
[/====================]
[section Hello World! ]
[/====================]

If all you want to do is to time a program's execution, here is a complete program (stopclock_example.cpp):

    #include <boost/chrono.hpp>
    #include <cmath>

    int main()
    {
        boost::chrono::system_clock::time_point start = boost::chrono::system_clock::now();

        for ( long i = 0; i < 10000000; ++i )
        std::sqrt( 123.456L ); // burn some time

        boost::chrono::__duration<double> sec = boost::chrono::system_clock::now() - start;
        std::cout << "took " << sec.count() << " seconds\n";
        return 0;
    }

Output was:

    took 0.832 seconds


[endsect]

[endsect]


[section Tutorial]

[section Duration]

The __duration is the heart of this library. The interface that the user will see in everyday use is nearly identical to that of [*Boost.DateTime] time __durations authored by Jeff Garland, both in syntax and in behavior. This has been a very popular boost library for 7 years. There is an enormous positive history with this interface.

The library consists of six units of time __duration:

* __hours
* __minutes
* __seconds
* __milliseconds__
* __microseconds
* __nanoseconds

These units were chosen as a subset of the boost library because they are the most common units used when sleeping, waiting on a condition variable, or waiting to obtain the lock on a mutex. Each of these units is nothing but a thin wrapper around a signed integral count. That is, when you construct __minutes`(3)`, all that happens is a `3` is stored inside `minutes`. When you construct __microseconds`(3)`, all that happens is a `3` is stored inside __microseconds.

The only context in which these different types differ is when being converted to one another. At this time, unit-specific compile-time conversion constants are used to convert the source unit to the target unit. Only conversions from coarser units to finer units are allowed (in Boost). This restriction ensures that all conversions are always exact. That is, __microseconds can always represent any value __minutes has.

In [*Boost.DateTime], these units are united via inheritance. __Boost_Chrono__ instead unites these units through the class template __duration. That is, in __Boost_Chrono__ all six of the above units are nothing but typedefs to different instantiations of __duration. This change from Boost.DateTime has a far reaching positive impact, while not changing the syntax of the everyday use at all.

The most immediate positive impact is that the library can immediately generate any unit, with any precision it needs. This is sometimes necessary when doing comparisons or arithmetic between __durations of differing precision, assuming one wants the comparison and arithmetic to be exact.

A secondary benefit is that by publishing the class template __duration interface, user code can very easily create __durations with any precision they desire. The __ratio utility is used to specify the precision, so as long as the precision can be expressed by a rational constant with respect to seconds, this framework can exactly represent it (one third of a second is no problem, and neither is one third of a __femto second). All of this utility and flexibility comes at no cost just by making use of the no-run-time-overhead __ratio facility.

In Boost.DateTime, __hours does not have the same representation as __nanoseconds. The former is usually represented with a `long` whereas a `long long` is required for the latter. The reason for this is simply range. You don't need many hours to cover an extremely large range of time. But this isn't true of nanoseconds. Being able to reduce the sizeof overhead for some units when possible, can be a significant performance advantage.

__Boost_Chrono__ continues, and generalizes that philosophy. Not only can one specify the precision of a __duration, one can also specify its representation. This can be any integral type, or even a floating-point type. Or it can be a user-defined type which emulates an arithmetic type. The six predefined units all use signed integral types as their representation. And they all have a minimum range of [plusminus] 292 years. __nanoseconds needs 64 bits to cover that range. __hours needs only 23 bits to cover that range.


[section  So What Exactly is a `duration` and How Do I Use One?]

A __duration has a representation and a tick period (precision).

    template <class Rep, class Period = __ratio<1> > class duration;

The representation is simply any arithmetic type, or an emulation of such a type. The representation stores a count of ticks. This count is the only data member stored in a __duration. If the representation is floating-point, it can store fractions of a tick to the precision of the representation. The tick period is represented by a __ratio and is encoded into the __duration_s type, instead of stored. The tick period only has an impact on the behavior of the __duration when a conversion between different __durations is attempted. The tick period is completely ignored when simply doing arithmetic among like __durations.

__example

    typedef boost::chrono::__duration<long, boost::ratio<60> > minutes;
    minutes m1(3);                 // m1 stores 3
    minutes m2(2);                 // m2 stores 2
    minutes m3 = m1 + m2;          // m3 stores 5

    typedef boost::chrono::__duration<long long, boost::micro> microseconds;
    microseconds us1(3);           // us1 stores 3
    microseconds us2(2);           // us2 stores 2
    microseconds us3 = us1 + us2;  // us3 stores 5

    microseconds us4 = m3 + us3;   // us4 stores 300000005

In the final line of code above, there is an implicit conversion from minutes to microseconds, resulting in a relatively large number of microseconds.

If you need to access the tick count within a __duration, there is a member `count()` which simply returns the stored tick count.

    long long tc = us4.count();    // tc is 300000005

These __duration_s have very simple, very predictable, and very observable behavior. After all, this is really nothing but the time-tested interface of Jeff's boost time __duration library (unified with templates instead of inheritance).

[endsect]

[section What Happens if I Assign `m3 + us3` to `minutes` Instead of `microseconds`?]

    minutes m4 = m3 + us3;

It won't compile! The rationale is that implicit truncation error should not be allowed to happen. If this were to compile, then `m4` would hold `5`, the same value as `m3`. The value associated with `us3` has been effectively ignored. This is similar to the problem of assigning a double to an `int`: the fractional part gets silently discarded.
[endsect]

[section But What if the Truncation Behavior is What I Want to Do?]

There is a __duration_cast facility to explicitly ask for this behavior:

    minutes m4 = boost::chrono::__duration_cast<minutes>(m3 + us3);  // m4.count() == 5

In general, one can perform __duration arithmetic at will. If __duration_cast isn't used, and it compiles, the arithmetic is exact. If one wants to override this exact arithmetic behavior, __duration_cast can be used to explicitly specify that desire. The __duration_cast has the same efficiency as the implicit conversion, and will even be exact as often as it can.

You can use __duration_cast`<>` to convert the __duration into whatever units you desire.  This facility will round down (truncate) if an exact conversion is not possible.  For example:

    boost::chrono::__nanoseconds start;
    boost::chrono::__nanoseconds end;
    typedef boost::chrono::__milliseconds__ ms;
    ms d = boost::chrono::__duration_cast<ms>(end - start);

    // d now holds the number of milliseconds from start to end.

    std::cout << ms.count() << "ms\n";

We can convert to __nanoseconds, or some integral-based duration which __nanoseconds will always exactly convert to, then __duration_cast`<>` is unnecessary:

    typedef boost::chrono::__nanoseconds ns;
    ns d = end - start;
    std::cout << ns.count() << "ns\n";

If you need seconds with a floating-point representation you can also eliminate the __duration_cast`<>`:

    typedef boost::chrono::__duration<double> sec;  // seconds, stored with a double
    sec d = end - start;
    std::cout << sec.count() << "s\n";

If you're not sure if you need __duration_cast`<>` or not, feel free to try it without.  If the conversion is exact, or if the destination has a floating-point representation, it will compile: else it will not compile.


If you need to use __duration_cast`<>`, but want to round up, instead of down when the conversion is inexact, here is a handy little helper function to do so.  Writing it is actually a good starter project for understanding __Boost_Chrono__:

    template <class ToDuration, class Rep, class Period>
    ToDuration
    round_up(boost::chrono::__duration<Rep, Period> d)
    {
        // first round down
        ToDuration result = boost::chrono::__duration_cast<ToDuration>(d);
        if (result < d)  // comparisons are *always* exact
           ++result;     // increment by one tick period
        return result;
    }

    typedef boost::chrono::__milliseconds__ ms;
    ms d = round_up<ms>(end - start);
    // d now holds the number of milliseconds from start to end, rounded up.
    std::cout << ms.count() << "ms\n";

[endsect]

[section Trafficking in floating-point Durations]

I don't want to deal with writing `duration_cast` all over the place. I'm content with the precision of my floating-point representation.

Not a problem. When the destination of a conversion has floating-point representation, all conversions are allowed to happen implicitly.

    typedef boost::chrono::__duration<double, __ratio<60> > dminutes;
    dminutes dm4 = m3 + us3;  // dm4.count() == 5.000000083333333

[endsect]

[section How Expensive is All of this?]

If you were writing these conversions by hand, you could not make it more efficient. The use of __ratio ensures that all conversion constants are simplified as much as possible at compile-time. This usually results in the numerator or denominator of the conversion factor simplifying to `1`, and being subsequently ignored in converting the run-time values of the tick counts.

[endsect]

[section  How Complicated is it to Build a Function Taking a `duration` Parameter?]

There are several options open to the user:

* If the author of the function wants to accept any __duration, and is willing to work in floating-point __durations, he can simply use any floating-point __duration as the parameter:

          void f(boost::chrono::duration<double> d)  // accept floating-point seconds
          {
              // d.count() == 3.e-6 when passed boost::chrono::microseconds(3)
          }

          f(boost::chrono::microseconds(3));

* If the author of the function wants to traffic only in integral __durations, and is content with handling nothing finer than say nanoseconds (just as an example), he can simply specify nanoseconds as the parameter:

          void f(boost::chrono::nanoseconds d)
          {
              // d.count() == 3000 when passed boost::chrono::microseconds(3)
          }

          f(boost::chrono::microseconds(3));

In this design, if the client wants to pass in a floating-point __duration, or a __duration of finer precision than nanoseconds, then the client is responsible for choosing his own rounding mode in the conversion to nanoseconds.

          boost::chrono::__duration<double> s(1./3);  // 1/3 of a second
          f(boost::chrono::duration_cast<boost::chrono::nanoseconds>(s));  // round towards zero in conversion to nanoseconds

In the example above, the client of f has chosen "round towards zero" as the desired rounding mode to nanoseconds. If the client has a __duration that won't exactly convert to nanoseconds, and fails to choose how the conversion will take place, the compiler will refuse the call:

        f(s);  // does not compile

* If the author of the function wants to accept any __duration, but wants to work with integral representations and wants to control the rounding mode internally, then he can template the function:

        template <class Rep, class Period>
        void f(boost::chrono::__duration<Rep, Period> d)
        {
            // convert d to nanoseconds, rounding up if it is not an exact conversion
            boost::chrono::nanoseconds ns = boost::chrono::duration_cast<boost::chrono::nanoseconds>(d);
            if (ns < d)
                ++ns;
            // ns.count() == 333333334 when passed 1/3 of a floating-point second
        }

          f(boost::chrono::__duration<double>(1./3));

*  If the author in the example does not want to accept floating-point based __durations, he can enforce that behavior like so:

        template <class Period>
        void f(boost::chrono::__duration<long long, Period> d)
        {
            // convert d to nanoseconds, rounding up if it is not an exact conversion
            boost::chrono::nanoseconds ns = boost::chrono::duration_cast<nanoseconds>(d);
            if (ns < d)
                ++ns;
            // ns.count() == 333333334 when passed 333333333333 picoseconds
        }
        // About 1/3 of a second worth of picoseconds
        f(boost::chrono::__duration<long long, boost::pico>(333333333333));

Clients with floating-point __durations who want to use f will now have to convert to an integral __duration themselves before passing the result to f.

In summary, the author of f has quite a bit of flexibility and control in the interface he wants to provide his clients with, and easy options for manipulating that __duration internal to his function.
[endsect]

[section Is it possible for the user to pass a __duration to a function with the units being ambiguous?]

No. No matter which option the author of `f` chooses above, the following client code will not compile:

    f(3);  // Will not compile, 3 is not implicitly convertible to any __duration

[endsect]

[section Can Durations Overflow?]

This depend on the representation. The default typedefs uses a representation that don't handle overflows. The user can define his own representation that manage overflow as required by its application.

[endsect]
[endsect]

[section Clocks]

While __durations only have precision and representation to concern themselves, clocks and __time_points are intimately related and refer to one another. Because clocks are simpler to explain, we will do so first without fully explaining __time_points. Once clocks are introduced, it will be easier to then fill in what a __time_point is.

A clock is a concept which bundles 3 things:

# A concrete __duration type.
# A concrete __time_point type.
# A function called now() which returns the concrete __time_point.

The standard defines tree system-wide clocks that are associated to the computer time.

* __system_clock represents system-wide realtime clock that can be synchronized with an external clock.

* __steady_clock can not be changed explicitly and the time since the initial epoch increase in a steady way.

* __high_resolution_clock intend to use the system-wide clock provided by the platform with the higest resolution.

__Boost_Chrono__ provides them when supported by the underlying platform. A given platform may not be able to supply all three of these clocks.

The library adds some clocks that are specific to a process or a thread, that is there is a clock per process or per thread.


The user is also able to easily create more clocks.

Given a clock named Clock, it will have:

    class Clock {
    public:
        typedef an arithmetic-like type        rep;
        typedef an instantiation of ratio      period;
        typedef boost::chrono::__duration<rep, period> __duration;
        typedef boost::chrono::__time_point<Clock>     time_point;
        static constexpr bool is_steady =      true or false;

        static time_point now();
    };

One can get the current time from Clock with:

    Clock::time_point t1 = Clock::now();

And one can get the time __duration between two __time_points associated with Clock with:

    Clock::duration d = Clock::now() - t1;

And one can specify a past or future __time_point with:

    Clock::time_point t2 = Clock::now() + d;

Note how even if a particular clock becomes obsolete, the next clock in line will have the same API. There is no new learning curve to come up. The only source code changes will be simply changing the type of the clock. The same __duration and __time_point framework continues to work as new clocks are introduced. And multiple clocks are safely and easily handled within the same program.


[endsect]


[section Time Point]

A __time_point represents a point in time, as opposed to a __duration of time. Another way of saying the same thing, is that a __time_point represents an epoch plus or minus a __duration. Examples of __time_points include:

* 3 minutes after the computer booted.
* 03:14:07 UTC on Tuesday, January 19, 2038
* 20 milliseconds after I started that timer.

In each of the examples above, a different epoch is implied. Sometimes an epoch has meaning for several millennia. Other times the meaning of an epoch is lost after a while (such as the start of a timer, or when the computer booted). However, if two __time_points are known to share the same epoch, they can be subtracted, yielding a valid __duration, even if the definition of the epoch no longer has meaning.

In __Boost_Chrono__, an epoch is a purely abstract and unspecified concept. There is no type representing an epoch. It is simply an idea that relates (or doesn't) __time_points to a clock, and in the case that they share a clock, __time_points to one another. __time_points associated with different clocks are generally not interoperable unless the relationship between the epochs associated with each clock is known.

[section  So What Exactly is a `time_point` and How Do I Use One?]

A __time_point has a clock and a __duration.

    template <class Clock, class Duration = typename Clock::duration> class __time_point;

The __time_point's clock is not stored. It is simply embedded into the __time_point's type and serves two purposes:

# Because __time_points originating from different clocks have different types, the compiler can be instructed to fail if incompatible __time_points are used in inappropriate ways.
# Given a __time_point, one often needs to compare that __time_point to "now". This is very simple as long as the __time_point knows what clock it is defined with respect to.

A __time_point's __duration is stored as the only data member of the __time_point. Thus __time_points and their corresponding __duration have exactly the same layout. But they have very different meanings. For example, it is one thing to say I want to sleep for 3 minutes. It is a completely different thing to say I want to sleep until 3 minutes past the time I started that timer (unless you just happened to start that timer now). Both meanings (and options for sleeping) have great practical value in common use cases for sleeping, waiting on a condition variable, and waiting for a mutex's lock. These same concepts and tools are found (for example) in Ada.

A timer example:

    void f()
    {
        boost::chrono::steady_clock::time_point start = boost::chrono::steady_clock::now();
        g();
        h();
        __duration<double> sec = boost::chrono::steady_clock::now() - start;
        cout << "f() took " << sec.count() << " seconds\n";
    }

Note that if one is using the __duration between two clock __time_points in a way where the precision of the __duration matters, it is good practice to convert the clock's  __duration to a known __duration. This insulates the code from future changes which may be made to the clock's  precision in the future. For example __steady_clock could easily be based on the clock speed of the cpu. When you upgrade to a faster machine, you do not want your code that assumed a certain tick period of this clock to start experiencing run-time failures because your timing code has silently changed meaning.

A delay loop example:

    // delay for at least 500 nanoseconds:
    auto go = boost::chrono::steady_clock::now() + boost::chrono::nanoseconds(500);
    while (boost::chrono::steady_clock::now() < go)
        ;

The above code will delay as close as possible to half a microsecond, no matter what the precision of __steady_clock is. The more precise __steady_clock becomes, the more accurate will be the delay to 500 nanoseconds.


[endsect]



[/
[section How to Define a Thread Clock]

On posix systems for which the macro _POSIX_THREAD_CPUTIME is defined we can get the time associated to a specific thread.

    class thread_clock {
    public:
        typedef __nanoseconds                          duration;
        typedef duration::rep                        rep;
        typedef duration::period                     period;
        typedef chrono::__time_point<thread_clock>    time_point;
        static constexpr bool is_steady =            BOOST_CHRONO_THREAD_CLOCK_IS_STEADY;

        static time_point now( ) {
            // get the current thread
            pthread_t pth=pthread_self(void);
            // get the clock_id associated to the current thread
            clockid_t clock_id;
            pthread_getcpuclockid(pth, clock_id);
            // get the timespec associated to the thread clock
            struct timespec ts;
            if ( ::clock_gettime( clock_id, &ts ) )
            {
                boost::throw_exception(
                system::system_error( errno, system::system_category, "chrono::thread_clock" ));
            }

            // transform to nanoseconds
            return time_point(duration(
                static_cast<thread_clock::rep>( ts.tv_sec ) * 1000000000 + ts.tv_nsec));

        }
        static time_point now( system::error_code & ec ) {
            // get the current thread
            pthread_t pth=pthread_self(void);
            // get the clock_id associated to the current thread
            clockid_t clock_id;
            pthread_getcpuclockid(pth, clock_id);
            // get the timespec associated to the thread clock
            struct timespec ts;
            if ( ::clock_gettime( clock_id, &ts ) )
            {
              ec.assign( errno, system::system_category );
              return time_point();
            }
            ec.clear();
            // transform to nanoseconds
            return time_point(duration(
                static_cast<thread_clock::rep>( ts.tv_sec ) * 1000000000 + ts.tv_nsec));
        }
    };

[endsect]
]


[endsect]

[section Specific Clocks]
[section system_clock]

__system_clock is useful when you need to correlate the time with a known epoch so you can convert it to a calendar time. Note the specific functions in the __system_clock class.


[endsect]
[section steady_clock]

__steady_clock is useful when you need to wait for a specific amount of time. __steady_clock time can not be reset. As other steady clocks, it is usually based on the processor tick.

Here is a polling solution, but it will probably be too inefficient:

    boost::chrono::__steady_clock::time_point start= chrono::__steady_clock::now();
    boost::chrono::__steady_clock::duration delay= chrono::seconds(5);
    while (boost::chrono::__steady_clock::now() - start <= delay) {}

[endsect]

[section high_resolution_clock]

When available, __high_resolution_clock is usually more expensive than the other system-wide clocks, so they are used only when the provided resolution is required to the application.

[endsect]

[section process_cpu_clock]

Process and thread clocks are used usually to measure the time spent by code blocks, as a basic time-spent profiling of different blocks of code (Boost.Stopwatch is a clear example of this use).

[endsect]

[section thread_clock]

You can use __thread_clock whenever you want to measure the time spent by the current thread. For example:

    boost::chrono::__thread_clock::time_point start=boost::chrono::__thread_clock::now();
    // ... do something ...

    typedef boost::chrono::__milliseconds__ ms;
    ms d = boost::chrono::__thread_clock::now() - start;
    // d now holds the number of milliseconds from start to end.
    std::cout << ms.count() << "ms\n";

If you need seconds with a floating-point representation you can do:

    typedef boost::chrono::__duration<double> sec;  // seconds, stored with a double.
    sec d = end - start;
    std::cout << sec.count() << "s\n";

If you would like to programmatically inspect `__thread_clock::duration`, you can get the representation type with `__thread_clock::rep`, and the tick period with `__thread_clock::period` (which should be a type __ratio which has nested values `__ratio::num` and `__ratio::den`).  The tick period of __thread_clock is `__thread_clock::period::num / __thread_clock::period::den` seconds: `1/1000000000` in this case (`1` billionth of a second), stored in a `long long`.

[endsect]
[endsect]

[section I/O]

Any __duration can be streamed out to a `basic_ostream`. The run-time value of the __duration is formatted according to the rules and current format settings for __duration`::rep`. This is followed by a single space and then the compile-time unit name of the __duration. This unit name is built on the string returned from `ratio_string<>` and the data used to construct the __duration_punct which was inserted into the stream's locale. If a __duration_punct has not been inserted into the stream's locale, a default constructed __duration_punct will be added to the stream's locale.

__duration unit names come in two varieties: long and short. The default constructed __duration_punct provides names in the long format. These names are English descriptions. Other languages are supported by constructing a __duration_punct with the proper spellings for "hours", "minutes" and "seconds", and their abbreviations (for the short format). The short or long format can be easily chosen by streaming a `duration_short()` or `duration_long()` manipulator respectively.

A __time_point is formatted by outputting its internal __duration followed by a string that describes the __time_point`::clock` epoch. This string will vary for each distinct clock, and for each implementation of the supplied clocks.

__example

    #include <iostream>
    #include <boost/chrono/chrono_io.hpp>

    int main()
    {
        using namespace std;
        using namespace boost;

        cout << "milliseconds(3) + microseconds(10) = "
             <<  boost::chrono::milliseconds(3) + boost::chrono::microseconds(10) << '\n';

        cout << "hours(3) + minutes(10) = "
             <<  boost::chrono::hours(3) + boost::chrono::minutes(10) << '\n';

        typedef boost::chrono::duration<long long, boost::ratio<1, 2500000000> > ClockTick;
        cout << "ClockTick(3) + boost::chrono::nanoseconds(10) = "
             <<  ClockTick(3) + boost::chrono::nanoseconds(10) << '\n';

        cout << "\nSet cout to use short names:\n";
        cout << boost::chrono::duration_short;

        cout << "milliseconds(3) + microseconds(10) = "
             <<  boost::chrono::milliseconds(3) + boost::chrono::microseconds(10) << '\n';

        cout << "hours(3) + minutes(10) = "
             <<  boost::chrono::hours(3) + boost::chrono::minutes(10) << '\n';

        cout << "ClockTick(3) + nanoseconds(10) = "
             <<  ClockTick(3) + boost::chrono::nanoseconds(10) << '\n';

        cout << "\nsystem_clock::now() = " << boost::chrono::system_clock::now() << '\n';
    #ifdef BOOST_CHRONO_HAS_CLOCK_STEADY
        cout << "steady_clock::now() = " << boost::chrono::steady_clock::now() << '\n';
    #endif
        cout << "\nSet cout to use long names:\n"
                << boost::chrono::duration_long
                << "high_resolution_clock::now() = "
                << boost::chrono::high_resolution_clock::now() << '\n';
        return 0;
    }

The output could be

    milliseconds(3) + microseconds(10) = 3010 microseconds
    hours(3) + minutes(10) = 190 minutes
    ClockTick(3) + nanoseconds(10) = 56 [1/5000000000]seconds

    Set cout to use short names:
    milliseconds(3) + microseconds(10) = 3010 [mu]s
    hours(3) + minutes(10) = 190 m
    ClockTick(3) + nanoseconds(10) = 56 [1/5000000000]s

    system_clock::now() = 129387415616250000 [1/10000000]s since Jan 1, 1970
    monotonic_clock::now() = 37297387636417 ns since boot

    Set cout to use long names:
    high_resolution_clock::now() = 37297387655134 nanoseconds since boot

Parsing a __duration follows rules analogous to the __duration converting constructor. A value and a unit (short or long) are read from the `basic_istream`. If the __duration has an integral representation, then the value parsed must be exactly representable in the target __duration (after conversion to the target __duration units), else `failbit` is set. __durations based on floating-point representations can be parsed using any units that do not cause overflow.

For example a stream containing "5000 milliseconds" can be parsed into seconds, but if the stream contains "5001 milliseconds", parsing into `seconds` will cause `failbit` to be set.

__example

    #include <boost/chrono/chrono_io.hpp>
    #include <sstream>
    #include <cassert>

    int main()
    {
        using namespace std;

        istringstream in("5000 milliseconds 4000 ms 3001 ms");
        boost::chrono::seconds d(0);
        in >> d;
        assert(in.good());
        assert(d == seconds(5));
        in >> d;
        assert(in.good());
        assert(d == seconds(4));
        in >> d;
        assert(in.fail());
        assert(d == seconds(4));

        return 0;
    }


Note that a __duration failure may occur late in the parsing process. This means that the characters making up the failed parse in the stream are usually consumed despite the failure to successfully parse.

Parsing a __time_point involves first parsing a __duration and then parsing the epoch string. If the epoch string does not match that associated with `time_point::clock` then failbit will be set.

__example

    #include <boost/chrono/chrono_io.hpp>
    #include <sstream>
    #include <iostream>
    #include <cassert>

    int main()
    {
        using namespace std;

        boost::chrono::high_resolution_clock::time_point t0 = boost::chrono::high_resolution_clock::now();
        stringstream io;
        io << t0;
        boost::chrono::high_resolution_clock::time_point t1;
        io >> t1;
        assert(!io.fail());
        cout << io.str() << '\n';
        cout << t0 << '\n';
        cout << t1 << '\n';
        boost::chrono::high_resolution_clock::time_point t = boost::chrono::high_resolution_clock::now();
        cout << t << '\n';

        cout << "That took " << t - t0 << '\n';
        cout << "That took " << t - t1 << '\n';

        return 0;
    }

The output could be:

    50908679121461 nanoseconds since boot
    That took 649630 nanoseconds

Here's a simple example to find out how many hours the computer has been up (on this platform):

    #include <boost/chrono/chrono_io.hpp>
    #include <iostream>

    int main()
    {
        using namespace std;
        using namespace boost;

        typedef boost::chrono::time_point<boost::chrono::steady_clock, boost::chrono::duration<double, boost::ratio<3600> > > T;
        T tp = boost::chrono::steady_clock::now();
        std::cout << tp << '\n';
        return 0;
    }

The output could be:

    17.8666 hours since boot

[endsect]

[endsect]
[/===============]
[section Examples]
[/===============]



[section Duration]

[/===============]
[section How you Override the Duration's Default Constructor]

Next we show how to override the __duration_s default constructor to do anything you want (in this case set it to zero). All we need to do is to change the representation

    namespace I_dont_like_the_default_duration_behavior {

    template <class R>
    class zero_default
    {
    public:
        typedef R rep;

    private:
        rep rep_;
    public:
        zero_default(rep i = 0) : rep_(i) {}
        operator rep() const {return rep_;}

        zero_default& operator+=(zero_default x) {rep_ += x.rep_; return *this;}
        zero_default& operator-=(zero_default x) {rep_ -= x.rep_; return *this;}
        zero_default& operator*=(zero_default x) {rep_ *= x.rep_; return *this;}
        zero_default& operator/=(zero_default x) {rep_ /= x.rep_; return *this;}

        zero_default  operator+ () const {return *this;}
        zero_default  operator- () const {return zero_default(-rep_);}
        zero_default& operator++()       {++rep_; return *this;}
        zero_default  operator++(int)    {return zero_default(rep_++);}
        zero_default& operator--()       {--rep_; return *this;}
        zero_default  operator--(int)    {return zero_default(rep_--);}

        friend zero_default operator+(zero_default x, zero_default y) {return x += y;}
        friend zero_default operator-(zero_default x, zero_default y) {return x -= y;}
        friend zero_default operator*(zero_default x, zero_default y) {return x *= y;}
        friend zero_default operator/(zero_default x, zero_default y) {return x /= y;}

        friend bool operator==(zero_default x, zero_default y) {return x.rep_ == y.rep_;}
        friend bool operator!=(zero_default x, zero_default y) {return !(x == y);}
        friend bool operator< (zero_default x, zero_default y) {return x.rep_ < y.rep_;}
        friend bool operator<=(zero_default x, zero_default y) {return !(y < x);}
        friend bool operator> (zero_default x, zero_default y) {return y < x;}
        friend bool operator>=(zero_default x, zero_default y) {return !(x < y);}
    };

    typedef boost::chrono::__duration<zero_default<long long>, boost::nano        > nanoseconds;
    typedef boost::chrono::__duration<zero_default<long long>, boost::micro       > microseconds;
    typedef boost::chrono::__duration<zero_default<long long>, boost::milli       > milliseconds;
    typedef boost::chrono::__duration<zero_default<long long>                      > seconds;
    typedef boost::chrono::__duration<zero_default<long long>, boost::ratio<60>   > minutes;
    typedef boost::chrono::__duration<zero_default<long long>, boost::ratio<3600> > hours;
    }

Usage

    using namespace I_dont_like_the_default_duration_behavior;

    milliseconds ms;
    std::cout << ms.count() << '\n';

['See the source file [@boost:libs/chrono/example/i_dont_like_the_default_duration_behavior.cpp example/i_dont_like_the_default_duration_behavior.cpp]]

[endsect]
[/
[/=========================]
[section runtime_resolution]

This example shows how to handle duration with resolution not known until run-time

    class duration
    {
    public:
        typedef long long rep;
    private:
        rep rep_;

        static const double ticks_per_nanosecond;

    public:
        typedef boost::chrono::duration<double, boost::nano> tonanosec;

        duration() {} // = default;
        explicit duration(const rep& r) : rep_(r) {}

        // conversions
        explicit duration(const tonanosec& d)
                : rep_(static_cast<rep>(d.count() * ticks_per_nanosecond)) {}

        // explicit
           operator tonanosec() const {return tonanosec(rep_/ticks_per_nanosecond);}

        // observer

        rep count() const {return rep_;}

        // arithmetic

        duration& operator+=(const duration& d) {rep_ += d.rep_; return *this;}
        duration& operator-=(const duration& d) {rep_ += d.rep_; return *this;}
        duration& operator*=(rep rhs)           {rep_ *= rhs; return *this;}
        duration& operator/=(rep rhs)           {rep_ /= rhs; return *this;}

        duration  operator+() const {return *this;}
        duration  operator-() const {return duration(-rep_);}
        duration& operator++()      {++rep_; return *this;}
        duration  operator++(int)   {return duration(rep_++);}
        duration& operator--()      {--rep_; return *this;}
        duration  operator--(int)   {return duration(rep_--);}

        friend duration operator+(duration x, duration y) {return x += y;}
        friend duration operator-(duration x, duration y) {return x -= y;}
        friend duration operator*(duration x, rep y)      {return x *= y;}
        friend duration operator*(rep x, duration y)      {return y *= x;}
        friend duration operator/(duration x, rep y)      {return x /= y;}

        friend bool operator==(duration x, duration y) {return x.rep_ == y.rep_;}
        friend bool operator!=(duration x, duration y) {return !(x == y);}
        friend bool operator< (duration x, duration y) {return x.rep_ < y.rep_;}
        friend bool operator<=(duration x, duration y) {return !(y < x);}
        friend bool operator> (duration x, duration y) {return y < x;}
        friend bool operator>=(duration x, duration y) {return !(x < y);}
    };

['See the source file [@boost:libs/chrono/example/runtime_resolution.cpp here]]

[endsect]
]
[/================]
[section Saturating]

A "saturating" signed integral type is developed.  This type has +/- infinity and a NaN (like IEEE floating-point) but otherwise obeys signed integral arithmetic. This class is subsequently used as the template parameter Rep in boost::chrono::__duration to demonstrate a duration class that does not silently ignore overflow.

['See the source file [@boost:libs/chrono/example/saturating.cpp example/saturating.cpp]]

[endsect]



[/==================]
[section xtime Conversions]

Example round_up utility:  converts d to To, rounding up for inexact conversions
Being able to *easily* write this function is a major feature!

    #include <boost/chrono.hpp>
    #include <boost/type_traits.hpp>

    #include <iostream>

    template <class To, class Rep, class Period>
    To
    round_up(boost::chrono::duration<Rep, Period> d)
    {
        To result = boost::chrono::duration_cast<To>(d);
        if (result < d)
            ++result;
        return result;
    }

To demonstrate interaction with an xtime-like facility:


    struct xtime
    {
        long sec;
        unsigned long usec;
    };

    template <class Rep, class Period>
    xtime
    to_xtime_truncate(boost::chrono::__duration<Rep, Period> d)
    {
        xtime xt;
        xt.sec = static_cast<long>(boost::chrono::__duration_cast<__seconds>(d).count());
        xt.usec = static_cast<long>(boost::chrono::__duration_cast<__microseconds>(d - __seconds(xt.sec)).count());
        return xt;
    }

    template <class Rep, class Period>
    xtime
    to_xtime_round_up(boost::chrono::__duration<Rep, Period> d)
    {
        xtime xt;
        xt.sec = static_cast<long>(boost::chrono::__duration_cast<__seconds>(d).count());
        xt.usec = static_cast<unsigned long>(round_up<boost::chrono::__microseconds>(d - boost::chrono::__seconds(xt.sec)).count());
        return xt;
    }

    microseconds
    from_xtime(xtime xt)
    {
        return boost::chrono::__seconds(xt.sec) + boost::chrono::__microseconds(xt.usec);
    }

    void print(xtime xt)
    {
        std::cout << '{' << xt.sec << ',' << xt.usec << "}\n";
    }

Usage

        xtime xt = to_xtime_truncate(seconds(3) + boost::chrono::__milliseconds__(251));
        print(xt);
        boost::chrono::milliseconds ms = boost::chrono::__duration_cast<boost::chrono::__milliseconds__>(from_xtime(xt));
        std::cout << ms.count() << " milliseconds\n";
        xt = to_xtime_round_up(ms);
        print(xt);
        xt = to_xtime_truncate(boost::chrono::seconds(3) + __nanoseconds(999));
        print(xt);
        xt = to_xtime_round_up(boost::chrono::seconds(3) + __nanoseconds(999));
        print(xt);


['See the source file [@boost:libs/chrono/example/xtime.cpp xtime.cpp]]

[endsect]


[endsect]
[section Clocks]

[/==================]
[section Cycle count]

Users can easily create their own clocks, with both points in time and time durations which have a representation and precision of their own choosing. For example if there is a hardware counter which simply increments a count with each cycle of the cpu, one can very easily build clocks, time points and durations on top of that, using only a few tens of lines of code. Such systems can be used to call the time-sensitive threading API's such as sleep, wait on a condition variable, or wait for a mutex lock. The API proposed herein is not sensitive as to whether this is a 300MHz clock (with a 3 1/3 nanosecond tick period) or a 3GHz clock (with a tick period of  1/3 of a nanosecond). And the resulting code will be just as efficient as if the user wrote a special purpose clock cycle counter.


    #include <boost/chrono.hpp>
    #include <boost/type_traits.hpp>
    #include <iostream>

    template <long long speed>
    struct cycle_count
    {
        typedef typename boost::__ratio_multiply__<boost::__ratio<speed>, boost::__mega>::type
            frequency;  // Mhz
        typedef typename boost::__ratio_divide__<boost::__ratio<1>, frequency>::type period;
        typedef long long rep;
        typedef boost::chrono::__duration<rep, period> duration;
        typedef boost::chrono::__time_point<cycle_count> time_point;

        static time_point now()
        {
            static long long tick = 0;
            // return exact cycle count
            return time_point(duration(++tick));  // fake access to clock cycle count
        }
    };

    template <long long speed>
    struct approx_cycle_count
    {
        static const long long frequency = speed * 1000000;  // MHz
        typedef nanoseconds duration;
        typedef duration::rep rep;
        typedef duration::period period;
        static const long long nanosec_per_sec = period::den;
        typedef boost::chrono::__time_point<approx_cycle_count> time_point;

        static time_point now()
        {
            static long long tick = 0;
            // return cycle count as an approximate number of nanoseconds
            // compute as if nanoseconds is only duration in the std::lib
            return time_point(duration(++tick * nanosec_per_sec / frequency));
        }
    };

['See the source file [@boost:libs/chrono/example/cycle_count.cpp cycle_count.cpp]]

[endsect]

[/==================]
[section xtime_clock]

This example demonstrates the use of a timeval-like struct to be used as the representation type for both __duration and __time_point.

    class xtime {
    private:
        long tv_sec;
        long tv_usec;

        void fixup() {
            if (tv_usec < 0) {
                tv_usec += 1000000;
                --tv_sec;
            }
        }

    public:
        explicit xtime(long sec, long usec) {
            tv_sec = sec;
            tv_usec = usec;
            if (tv_usec < 0 || tv_usec >= 1000000) {
                tv_sec += tv_usec / 1000000;
                tv_usec %= 1000000;
                fixup();
            }
        }

        explicit xtime(long long usec) {
            tv_usec = static_cast<long>(usec % 1000000);
            tv_sec  = static_cast<long>(usec / 1000000);
            fixup();
        }

        // explicit
        operator long long() const {return static_cast<long long>(tv_sec) * 1000000 + tv_usec;}

        xtime& operator += (xtime rhs) {
            tv_sec += rhs.tv_sec;
            tv_usec += rhs.tv_usec;
            if (tv_usec >= 1000000) {
                tv_usec -= 1000000;
                ++tv_sec;
            }
            return *this;
        }

        xtime& operator -= (xtime rhs) {
            tv_sec -= rhs.tv_sec;
            tv_usec -= rhs.tv_usec;
            fixup();
            return *this;
        }

        xtime& operator %= (xtime rhs) {
            long long t = tv_sec * 1000000 + tv_usec;
            long long r = rhs.tv_sec * 1000000 + rhs.tv_usec;
            t %= r;
            tv_sec = static_cast<long>(t / 1000000);
            tv_usec = static_cast<long>(t % 1000000);
            fixup();
            return *this;
        }

        friend xtime operator+(xtime x, xtime y) {return x += y;}
        friend xtime operator-(xtime x, xtime y) {return x -= y;}
        friend xtime operator%(xtime x, xtime y) {return x %= y;}

        friend bool operator==(xtime x, xtime y)
            { return (x.tv_sec == y.tv_sec && x.tv_usec == y.tv_usec); }

        friend bool operator<(xtime x, xtime y) {
            if (x.tv_sec == y.tv_sec)
                return (x.tv_usec < y.tv_usec);
            return (x.tv_sec < y.tv_sec);
        }

        friend bool operator!=(xtime x, xtime y) { return !(x == y); }
        friend bool operator> (xtime x, xtime y) { return y < x; }
        friend bool operator<=(xtime x, xtime y) { return !(y < x); }
        friend bool operator>=(xtime x, xtime y) { return !(x < y); }

        friend std::ostream& operator<<(std::ostream& os, xtime x)
            {return os << '{' << x.tv_sec << ',' << x.tv_usec << '}';}
    };

Clock based on timeval-like struct.

    class xtime_clock
    {
    public:
        typedef xtime                                  rep;
        typedef boost::micro                           period;
        typedef boost::chrono::duration<rep, period>   duration;
        typedef boost::chrono::time_point<xtime_clock> time_point;

        static time_point now()
        {
        #if defined(BOOST_CHRONO_WINDOWS_API)
            time_point t(duration(xtime(0)));
            gettimeofday((timeval*)&t, 0);
            return t;

        #elif defined(BOOST_CHRONO_MAC_API)

            time_point t(duration(xtime(0)));
            gettimeofday((timeval*)&t, 0);
            return t;

        #elif defined(BOOST_CHRONO_POSIX_API)
            //time_point t(0,0);

            timespec ts;
            ::clock_gettime( CLOCK_REALTIME, &ts );

            xtime xt( ts.tv_sec, ts.tv_nsec/1000);
            return time_point(duration(xt));

        #endif  // POSIX
        }
    };

Usage of xtime_clock

        std::cout << "sizeof xtime_clock::time_point = " << sizeof(xtime_clock::time_point) << '\n';
        std::cout << "sizeof xtime_clock::duration = " << sizeof(xtime_clock::duration) << '\n';
        std::cout << "sizeof xtime_clock::rep = " << sizeof(xtime_clock::rep) << '\n';
        xtime_clock::duration delay(boost::chrono::milliseconds(5));
        xtime_clock::time_point start = xtime_clock::now();
        while (xtime_clock::now() - start <= delay) {}
        xtime_clock::time_point stop = xtime_clock::now();
        xtime_clock::duration elapsed = stop - start;
        std::cout << "paused " << boost::chrono::::nanoseconds(elapsed).count() << " nanoseconds\n";


['See the source file [@boost:libs/chrono/example/timeval_demo.cpp example/timeval_demo.cpp]]

[endsect]
[endsect]



[/
[/======================================================]
[section Howard Hinnant's original demonstration program]

['See the source file [@boost:libs/chrono/example/time2_demo.cpp example/time2_demo.cpp]]

[endsect]
]
[section Time Point]

[/==================]
[section min Utility]

The user can define a function returning the earliest __time_point as follows:

    template <class Clock, class Duration1, class Duration2>
    typename boost::__common_type<__time_point<Clock, Duration1>,
                         __time_point<Clock, Duration2> >::type
    min(__time_point<Clock, Duration1> t1, __time_point<Clock, Duration2> t2)
    {
        return t2 < t1 ? t2 : t1;
    }

Being able to *easily* write this function is a major feature!

    BOOST_AUTO(t1, system_clock::now() + seconds(3));
    BOOST_AUTO(t2, system_clock::now() + nanoseconds(3));
    BOOST_AUTO(t3, min(t1, t2));

['See the source file [@boost:libs/chrono/example/min_time_point.cpp example/min_time_point.cpp]]

[endsect]


[/===============================================================]
[section A Tiny Program that Times How Long Until a Key is Struck]

    #include <boost/chrono.hpp>
    #include <iostream>
    #include <iomanip>

    using namespace boost::chrono;

    template< class Clock >
    class timer
    {
      typename Clock::time_point start;
    public:
      timer() : start( Clock::now() ) {}
      typename Clock::duration elapsed() const
      {
        return Clock::now() - start;
      }
      double seconds() const
      {
        return elapsed().count() * ((double)Clock::period::num/Clock::period::den);
      }
    };

    int main()
    {
      timer<__system_clock> t1;
      timer<__steady_clock> t2;
      timer<__high_resolution_clock> t3;

      std::cout << "Type the Enter key: ";
      std::cin.get();

      std::cout << std::fixed << std::setprecision(9);
      std::cout << "system_clock-----------: "
                << t1.seconds() << " seconds\n";
      std::cout << "steady_clock--------: "
                << t2.seconds() << " seconds\n";
      std::cout << "high_resolution_clock--: "
                << t3.seconds() << " seconds\n";

      __system_clock::time_point d4 = __system_clock::now();
      __system_clock::time_point d5 = __system_clock::now();

      std::cout << "\nsystem_clock latency-----------: " << (d5 - d4).count() << std::endl;

      __steady_clock::time_point d6 = __steady_clock::now();
      __steady_clock::time_point d7 = __steady_clock::now();

      std::cout << "steady_clock latency--------: " << (d7 - d6).count() << std::endl;

      __high_resolution_clock::time_point d8 = __high_resolution_clock::now();
      __high_resolution_clock::time_point d9 = __high_resolution_clock::now();

      std::cout << "high_resolution_clock latency--: " << (d9 - d8).count() << std::endl;

      std::time_t now = __system_clock::to_time_t(__system_clock::now());

      std::cout << "\nsystem_clock::now() reports UTC is "
        << std::asctime(std::gmtime(&now)) << "\n";

      return 0;
    }

The output of this program run looks like this:




['See the source file [@boost:libs/chrono/example/await_keystroke.cpp example/await_keystroke.cpp]]

[endsect]

[/
[/===============================================================]
[section Time Command]

    #include <boost/chrono/stopclock.hpp>
    #include <cstdlib>
    #include <string>
    #include <iostream>

    int main( int argc, char * argv[] )
    {
      if ( argc == 1 )
      {
        std::cout << "invoke: timex [-v] command [args...]\n"
          "  command will be executed and timings displayed\n"
          "  -v option causes command and args to be displayed\n";
        return 1;
      }

      std::string s;

      bool verbose = false;
      if ( argc > 1 && *argv[1] == '-' && *(argv[1]+1) == 'v' )
      {
        verbose = true;
        ++argv;
        --argc;
      }

      for ( int i = 1; i < argc; ++i )
      {
        if ( i > 1 ) s += ' ';
        s += argv[i];
      }

      if ( verbose )
        { std::cout << "command: \"" << s.c_str() << "\"\n"; }

      boost::chrono::__stopclock__<> t;

      return std::system( s.c_str() );
    }

['See the source file [@boost:libs/chrono/example/timex.cpp example/timex.cpp]]

[endsect]
]

[section 24 Hours Display]

In the example above we take advantage of the fact that __time_points convert as long as they have the same clock, and as long as their internal __durations convert. We also take advantage of the fact that a __duration with a floating-point representation will convert from anything. Finally the I/O system discovers the more readable "hours" unit for our `duration<double, ratio<3600>>`.

There are many other ways to format __durations and __time_points. For example see [@http://en.wikipedia.org/wiki/ISO_8601#Durations ISO 8601]. Instead of coding every possibility into `operator<<`, which would lead to significant code bloat for even the most trivial uses, this document seeks to inform the reader how to write custom I/O when desired.

As an example, the function below streams arbitrary __durations to arbitrary `basic_ostreams` using the format:

    [-]d/hh:mm:ss.cc

Where:

* `d` is the number of `days`
* `h` is the number of `hours`
* `m` is the number of `minutes`
* `ss.cc` is the number of `seconds` rounded to the nearest hundreth of a second

    #include <boost/chrono/chrono_io.hpp>
    #include <ostream>
    #include <iostream>

    // format duration as [-]d/hh::mm::ss.cc
    template <class CharT, class Traits, class Rep, class Period>
    std::basic_ostream<CharT, Traits>&
    display(std::basic_ostream<CharT, Traits>& os,
            boost::chrono::duration<Rep, Period> d)
    {
        using namespace std;
        using namespace boost;

        typedef boost::chrono::duration<long long, boost::ratio<86400> > days;
        typedef boost::chrono::duration<long long, boost:centi> centiseconds;

        // if negative, print negative sign and negate
        if (d < boost::chrono::duration<Rep, Period>(0))
        {
            d = -d;
            os << '-';
        }
        // round d to nearest centiseconds, to even on tie
        centiseconds cs = boost::chrono::duration_cast<centiseconds>(d);
        if (d - cs > boost::chrono::milliseconds(5)
            || (d - cs == boost::chrono::milliseconds(5) && cs.count() & 1))
            ++cs;
        // separate seconds from centiseconds
        boost::chrono::seconds s = boost::chrono::duration_cast<boost::chrono::seconds>(cs);
        cs -= s;
        // separate minutes from seconds
        boost::chrono::minutes m = boost::chrono::duration_cast<boost::chrono::minutes>(s);
        s -= m;
        // separate hours from minutes
        boost::chrono::hours h = boost::chrono::duration_cast<boost::chrono::hours>(m);
        m -= h;
        // separate days from hours
        days dy = boost::chrono::duration_cast<days>(h);
        h -= dy;
        // print d/hh:mm:ss.cc
        os << dy.count() << '/';
        if (h < boost::chrono::hours(10))
            os << '0';
        os << h.count() << ':';
        if (m < boost::chrono::minutes(10))
            os << '0';
        os << m.count() << ':';
        if (s < boost::chrono::seconds(10))
            os << '0';
        os << s.count() << '.';
        if (cs < boost::chrono::centiseconds(10))
            os << '0';
        os << cs.count();
        return os;
    }

    int main()
    {
        using namespace std;
        using namespace boost;

        display(cout, boost::chrono::steady_clock::now().time_since_epoch()
                      + boost::chrono::duration<long, boost::mega>(1)) << '\n';
        display(cout, -boost::chrono::milliseconds(6)) << '\n';
        display(cout, boost::chrono::duration<long, boost::mega>(1)) << '\n';
        display(cout, -boost::chrono::duration<long, boost::mega>(1)) << '\n';
    }

The output could be:

    12/06:03:22.95
    -0/00:00:00.01
    11/13:46:40.00
    -11/13:46:40.00

[endsect]


[/=======================================================]
[section Simulated Thread Interface Demonstration Program]

The C++0x standard library's multi-threading library requires the ability to deal with the representation of time in a manner consistent with modern C++ practices. Next is a simulation of this interface.

The non-member sleep functions can be emulated as follows:

    namespace boost { namespace this_thread {

    template <class Rep, class Period>
    void sleep_for(const chrono::__duration<Rep, Period>& d) {
        chrono::__microseconds t = chrono::__duration_cast<chrono::__microseconds>(d);
        if (t < d)
            ++t;
        if (t > chrono::__microseconds(0))
            std::cout << "sleep_for " << t.count() << " microseconds\n";
    }

    template <class Clock, class Duration>
    void sleep_until(const chrono::__time_point<Clock, Duration>& t) {
        using namespace chrono;
        typedef __time_point<Clock, Duration> Time;
        typedef __system_clock::time_point SysTime;
        if (t > Clock::now()) {
            typedef typename __common_type<typename Time::duration,
                                         typename SysTime::duration>::type D;
            /* auto */ D d = t - Clock::now();
            microseconds us = __duration_cast<__microseconds>(d);
            if (us < d)
                ++us;
            SysTime st = __system_clock::now() + us;
            std::cout << "sleep_until    ";
            detail::print_time(st);
            std::cout << " which is " << (st - __system_clock::now()).count() << " microseconds away\n";
        }
    }

    }}


Next is the `boost::thread::timed_mutex` modified fuctions

    namespace boost {
    struct timed_mutex {
        // ...

        template <class Rep, class Period>
        bool try_lock_for(const chrono::__duration<Rep, Period>& d) {
            chrono::__microseconds t = chrono::__duration_cast<chrono::__microseconds>(d);
            if (t <= chrono::__microseconds(0))
                return try_lock();
            std::cout << "try_lock_for " << t.count() << " microseconds\n";
            return true;
        }

        template <class Clock, class Duration>
        bool try_lock_until(const chrono::__time_point<Clock, Duration>& t)
        {
            using namespace chrono;
            typedef __time_point<Clock, Duration> Time;
            typedef __system_clock::time_point SysTime;
            if (t <= Clock::now())
                return try_lock();
            typedef typename __common_type<typename Time::duration,
              typename Clock::duration>::type D;
            /* auto */ D d = t - Clock::now();
            microseconds us = __duration_cast<__microseconds>(d);
            SysTime st = __system_clock::now() + us;
            std::cout << "try_lock_until ";
            detail::print_time(st);
            std::cout << " which is " << (st - __system_clock::now()).count()
              << " microseconds away\n";
            return true;
        }
    };
    }

`boost::thread::condition_variable` time related function are modified as follows:

    namespace boost {
    struct condition_variable
    {
        // ...

        template <class Rep, class Period>
        bool wait_for(mutex&, const chrono::__duration<Rep, Period>& d) {
            chrono::microseconds t = chrono::__duration_cast<chrono::microseconds>(d);
            std::cout << "wait_for " << t.count() << " microseconds\n";
            return true;
        }

        template <class Clock, class Duration>
        bool wait_until(mutex&, const chrono::__time_point<Clock, Duration>& t) {
            using namespace boost::chrono;
            typedef __time_point<Clock, Duration> Time;
            typedef __system_clock::time_point SysTime;
            if (t <= Clock::now())
                return false;
            typedef typename __common_type<typename Time::duration,
              typename Clock::duration>::type D;
            /* auto */ D d = t - Clock::now();
            microseconds us = __duration_cast<__microseconds>(d);
            SysTime st = __system_clock::now() + us;
             std::cout << "wait_until     ";
            detail::print_time(st);
            std::cout << " which is " << (st - __system_clock::now()).count()
              << " microseconds away\n";
            return true;
        }
    };
    }

Next follows how simple is the usage of this functions:

    boost::mutex m;
    boost::timed_mutex mut;
    boost::condition_variable cv;

    using namespace boost;

    this_thread::sleep_for(chrono::__seconds(3));
    this_thread::sleep_for(chrono::__nanoseconds(300));
    chrono::__system_clock::time_point time_limit = chrono::__system_clock::now() + chrono::__seconds_(4) + chrono::__milliseconds__(500);
    this_thread::sleep_until(time_limit);

    mut.try_lock_for(chrono::__milliseconds__(30));
    mut.try_lock_until(time_limit);

    cv.wait_for(m, chrono::__minutes(1));    // real code would put this in a loop
    cv.wait_until(m, time_limit);  // real code would put this in a loop

    // For those who prefer floating-point
    this_thread::sleep_for(chrono::__duration<double>(0.25));
    this_thread::sleep_until(chrono::__system_clock::now() + chrono::__duration<double>(1.5));


['See the source file [@boost:libs/chrono/example/simulated_thread_interface_demo.cpp example/simulated_thread_interface_demo.cpp]]

[endsect]

[endsect]
[section IO]
[/=======================================================]
[section:french French Output]

Example use of output in French

    #include <boost/chrono/chrono_io.hpp>
    #include <iostream>
    #include <locale>

    int main()
    {
        using namespace std;
        using namespace boost;
        using namespace boost::chrono;

        cout.imbue(locale(locale(), new duration_punct<char>
            (
                duration_punct<char>::use_long,
                "secondes", "minutes", "heures",
                "s", "m", "h"
            )));
        hours h(5);
        minutes m(45);
        seconds s(15);
        milliseconds ms(763);
        cout << h << ", " << m << ", " << s << " et " << ms << '\n';
    }

Output is:

    5 heures, 45 minutes, 15 secondes et 763 millisecondes

['See the source file [@boost:libs/chrono/example/french.cpp example/french.cpp]]

[endsect] [/section:french French Output]
[endsect] [/section IO]

[endsect] [/section Examples]


[/================================]
[section:ext_references External Resources]
[/================================]

[variablelist

[
    [[@http://www.open-std.org/jtc1/sc22/wg21 [*C++ Standards Committee's current Working Paper]]]
    [The most authoritative reference material for the library is the C++ Standards Committee's current Working Paper (WP).  20.11 Time utilities "time"]
]

[
    [[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm [*N2661 - A Foundation to Sleep On]]]
    [From Howard E. Hinnant, Walter E. Brown, Jeff Garland  and Marc Paterno. Is very informative and provides motivation for key design decisions]
]


[
    [[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3134.html#934 [*LGW 934. duration is missing operator%]]]
    [From Terry Golubiewski. Is very informative and provides motivation for key design decisions]
]

[
    [[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3135.html#935 [*LGW 935. clock error handling needs to be specified]]]
    [From Beman Dawes. This issue has been stated as NAD Future.]
]

]

[endsect]

[endsect]

[/=================]
[section:reference Reference ]
[/=================]

As `constexpr` will not be supported by some compilers, it is replaced in the code by BOOST_CHRONO_CONSTEXPR for constexpr functions and BOOST_CHRONO_STATIC_CONSTEXPR for struct/class static fields. The documentation doesn't use these macros.

[section:cpp0x Included on the C++0x Recommendation]


[/=============================================]
[section:chrono_hpp Header `<boost/chrono.hpp>`]
[/=============================================]

    #include <boost/chrono/duration.hpp>
    #include <boost/chrono/time_point.hpp>
    #include <boost/chrono/system_clocks.hpp>
    #include <boost/chrono/typeof/boost/chrono/chrono.hpp>

[section:limitations Limitations and Extensions]

Next follows limitation respect to the C++0x recomendations:

* constexpr not tested yet.
* The recently steady_clock approved is not yet included.

The current implementation provides in addition:

* clock error handling as specified in [@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3135.html#935 clock error handling needs to be specified].
* process and thread clocks.


[endsect]

[section:conf Configuration Macros]

[section:assert How Assert Behaves?]

When `BOOST_NO_STATIC_ASSERT` is defined, the user can select the way static assertions are reported. Define

* `BOOST_CHRONO_USES_STATIC_ASSERT`: define it if you want to use Boost.StaticAssert.
* `BOOST_CHRONO_USES_MPL_ASSERT`: define it if you want to use Boost.MPL static asertions.
* `BOOST_CHRONO_USES_ARRAY_ASSERT`: define it if you want to use internal static asertions.

The default behavior is as `BOOST_CHRONO_USES_ARRAY_ASSERT` was defined.

When `BOOST_CHRONO_USES_MPL_ASSERT` is not defined the following symbols are defined as

    #define BOOST_CHRONO_A_DURATION_REPRESENTATION_CAN_NOT_BE_A_DURATION \
        "A duration representation can not be a duration"
    #define BOOST_CHRONO_SECOND_TEMPLATE_PARAMETER_OF_DURATION_MUST_BE_A_STD_RATIO \
        "Second template parameter of duration must be a boost::ratio"
    #define BOOST_CHRONO_DURATION_PERIOD_MUST_BE_POSITIVE \
        "duration period must be positive"
    #define BOOST_CHRONO_SECOND_TEMPLATE_PARAMETER_OF_TIME_POINT_MUST_BE_A_BOOST_CHRONO_DURATION \
        "Second template parameter of time_point must be a boost::chrono::duration"

Depending on the static assertion used system you will have an hint of the failing assertion either through the symbol or through the text.

[endsect]

[section:header_only How to Build Boost.Chrono as a Header Only Library?]

When `BOOST_CHRONO_HEADER_ONLY` is defined the lib is header-only.

If in addition `BOOST_USE_WINDOWS_H` is defined `<windows.h>` is included, otherwise files in `boost/detail/win` are used to reduce the impact of including `<windows.h>`.

[endsect]


[endsect]



[endsect]

[/=============================================]
[section:duration_hpp Header `<boost/chrono/duration.hpp>`]
[/=============================================]

This file contains duration specific classes and non-member functions.

    namespace boost {
      namespace chrono {

        template <class Rep, class Period = __ratio<1> >  class __duration;

      }
      template <class Rep1, class Period1, class Rep2, class Period2>
      struct __common_type_spe<duration<Rep1, Period1>,
                         duration<Rep2, Period2> >;

      namespace chrono {

        // customization traits
        template <class Rep> struct __treat_as_floating_point;
        template <class Rep> struct __duration_values;

        // duration arithmetic
        template <class Rep1, class Period1, class Rep2, class Period2>
        typename common_type<duration<Rep1, Period1>, duration<Rep2, Period2> >::type
        operator+(
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);

        template <class Rep1, class Period1, class Rep2, class Period2>
        typename common_type<duration<Rep1, Period1>, duration<Rep2, Period2> >::type
        operator-(
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);

        template <class Rep1, class Period, class Rep2>
        duration<typename common_type<Rep1, Rep2>::type, Period>
        operator*(
            const duration<Rep1, Period>& d,
            const Rep2& s);

        template <class Rep1, class Period, class Rep2>
        duration<typename common_type<Rep1, Rep2>::type, Period>
        operator*(
            const Rep1& s,
            const duration<Rep2, Period>& d);

        template <class Rep1, class Period, class Rep2>
        duration<typename common_type<Rep1, Rep2>::type, Period>
        operator/(
            const duration<Rep1, Period>& d,
            const Rep2& s);

        template <class Rep1, class Period1, class Rep2, class Period2>
        typename common_type<Rep1, Rep2>::type
        operator/(
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);

        #ifdef BOOST_CHRONO_EXTENSIONS
        // Used to get frecuency of events
        template <class Rep1, class Rep2, class Period>
        double operator/(
            const Rep1& s,
            const duration<Rep2, Period>& d);
        #endif

        // duration comparisons
        template <class Rep1, class Period1, class Rep2, class Period2>
        constexpr bool operator==(
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);

        template <class Rep1, class Period1, class Rep2, class Period2>
        constexpr bool operator!=(
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);

        template <class Rep1, class Period1, class Rep2, class Period2>
        constexpr bool operator<(
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);
        template <class Rep1, class Period1, class Rep2, class Period2>
        constexpr bool operator<=(
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);

        template <class Rep1, class Period1, class Rep2, class Period2>
        constexpr bool operator> (
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);
        template <class Rep1, class Period1, class Rep2, class Period2>
        constexpr bool operator>=(
            const duration<Rep1, Period1>& lhs,
            const duration<Rep2, Period2>& rhs);

        // duration_cast

        template <class ToDuration, class Rep, class Period>
        ToDuration __duration_cast(const duration<Rep, Period>& d);

        // convenience typedefs
        typedef duration<boost::int_least64_t, nano> __nanoseconds;    // at least 64 bits needed
        typedef duration<boost::int_least64_t, micro> __microseconds;  // at least 55 bits needed
        typedef duration<boost::int_least64_t, milli> __milliseconds__;  // at least 45 bits needed
        typedef duration<boost::int_least64_t> __seconds;              // at least 35 bits needed
        typedef duration<boost::int_least32_t, ratio< 60> > __minutes; // at least 29 bits needed
        typedef duration<boost::int_least32_t, ratio<3600> > __hours;  // at least 23 bits needed

      }
    }


[section:traits Time-related Traits]

[section:treat_as_floating_point Metafunction `treat_as_floating_point<>`]

    template <class Rep> struct treat_as_floating_point
        : boost::is_floating_point<Rep> {};

The __duration template uses the __treat_as_floating_point trait to help determine if a __duration with one tick period can be converted to another __duration with a different tick period. If `treat_as_floating_point<Rep>::value` is `true`, then `Rep` is a floating-point type and implicit conversions are allowed among __durations. Otherwise, the implicit convertibility depends on the tick periods of the __durations. If `Rep` is a class type which emulates a floating-point type, the author of `Rep` can specialize __treat_as_floating_point so that __duration will treat this `Rep` as if it were a floating-point type. Otherwise `Rep` is assumed to be an integral type, or a class emulating an integral type.


[endsect]
[section:duration_values Class Template `duration_values`]

    template <class Rep>
    struct duration_values
    {
    public:
        static constexpr Rep __zero();
        static constexpr Rep __max();
        static constexpr Rep __min();
    };

The __duration template uses the __duration_values trait to construct special values of the __duration_s representation (`Rep`). This is done because the representation might be a class type with behavior which requires some other implementation to return these special values. In that case, the author of that class type should specialize __duration_values to return the indicated values.

[section:zero Static Member Function `zero()`]

    static constexpr Rep zero();

__returns `Rep(0)`. [*Note:] `Rep(0)` is specified instead of `Rep()` since `Rep()` may have some other meaning, such as an uninitialized value.

__remarks The value returned corresponds to the additive identity.

[endsect]
[section:max Static Member Function `max()`]

    static constexpr Rep max();

__returns `numeric_limits<Rep>::max()`.

__remarks The value returned compares greater than zero().

[endsect]
[section:min Static Member Function `min()`]

    static constexpr Rep min();

__returns `numeric_limits<Rep>::lowest()`.

__remarks The value returned compares less than or equal to `zero()`.

[endsect]

[endsect]

[endsect]

[section:common_type_spe `common_type` Specialization]

    template <class Rep1, class Period1, class Rep2, class Period2>
    struct __common_type<chrono::__duration<Rep1, Period1>, chrono::__duration<Rep2, Period2> >
    {
        typedef chrono::__duration<typename __common_type<Rep1, Rep2>::type, __see_bellow__> type;
    };

The period of the __duration indicated by this specialization of __common_type is the greatest common divisor of `Period1` and `Period2`. This can be computed by forming a __ratio of the greatest common divisor of `Period1::num` and `Period2::num`, and the least common multiple of `Period1::den` and `Period2::den`.

[*Note:] The typedef type is the __duration with the largest tick period possible where both __duration arguments will convert to it without requiring a division operation. The representation of this type is intended to be able to hold any value resulting from this conversion, with the possible exception of round-off error when floating-point __durations are involved (but not truncation error).

[endsect]


[section:duration Class Template `duration<>`]

A __duration measures time between two points in time (__time_point). A __duration has a representation which holds a count of ticks, and a tick period. The tick period is the amount of time which occurs from one tick to another in units of a second. It is expressed as a rational constant using __ratio.

    namespace boost { namespace chrono {

        template <class Rep, class Period>
        class duration {
        public:
            typedef Rep rep;
            typedef Period period;
        private:
            rep rep_; // exposition only
        public:
            constexpr duration();
            template <class Rep2>
            constexpr explicit duration(const Rep2& r);

            template <class Rep2, class Period2>
            constexpr duration(const duration<Rep2, Period2>& d);

            duration& operator=(const duration&) = default;

            constexpr rep count() const;

            constexpr duration  operator+();
            constexpr duration  operator-();
            duration& operator++();
            duration  operator++(int);
            duration& operator--();
            duration  operator--(int);

            duration& operator+=(const duration& d);
            duration& operator-=(const duration& d);

            duration& operator*=(const rep& rhs);
            duration& operator/=(const rep& rhs);
            duration& operator%=(const rep& rhs);
            duration& operator%=(const duration& rhs);

            static constexpr duration zero();
            static constexpr duration min();
            static constexpr duration max();
        };

    }}

`Rep` must be an arithmetic type, or a class emulating an arithmetic type, compile diagnostic otherwise. If __duration is instantiated with the type of `Rep` being a __duration, compile diagnostic is issued.

`Period` must be an instantiation of `ratio`, compile diagnostic otherwise.

`Period::num` must be positive, compile diagnostic otherwise.

Examples:

* `__duration<long, __ratio<60> >` holds a count of minutes using a long.

* `__duration<long long, milli>` holds a count of milliseconds using a long long.

* `__duration<double, __ratio<1, 30> >` holds a count using a double with a tick period of 1/30 second (a tick frequency of 30 Hz).

The following members of __duration do not throw an exception unless the indicated operations on the representations throw an exception.

[section:duration_c_1 Constructor `duration(const Rep2&)`]

    template <class Rep2>
    constexpr explicit duration(const Rep2& r);

__remarks `Rep2` is implicitly convertible to `rep`, and

* `treat_as_floating_point<rep>::value` is `true`, or
* `!treat_as_floating_point<rep>::value && !treat_as_floating_point<Rep2>::value` is `true`.

If these constraints are not met, this constructor will not participate in overload resolution. [*Note:] This requirement prevents construction of an integral-based __duration with a floating-point representation. Such a construction could easily lead to confusion about the value of the __duration.

__example

        __duration<int, milli> d(3.5);  // do not compile
        __duration<int, milli> d(3);    // ok

__effects  Constructs an object of type __duration.

__post_conditions `count() == static_cast<rep>(r)`.

[endsect]
[section:duration_c_2 Constructor `duration(const duration&)`]

    template <class Rep2, class Period2>
    constexpr __duration(const __duration<Rep2, Period2>& d);

__remarks `treat_as_floating_point<rep>::value`, or `ratio_divide<Period2, period>::type::den == 1`, else this constructor will not participate in overload resolution. [*note] This requirement prevents implicit truncation error when converting between integral-based __durations. Such a construction could easily lead to confusion about the value of the __duration.

__example

        __duration<int, milli> ms(3);
        __duration<int, micro> us = ms;  // ok
        __duration<int, milli> ms2 = us; // do not compile

__effects  Constructs an object of type __duration, constructing `rep_` from `duration_cast<__duration>(d).count()`.

[endsect]
[section:count Member Function `count() const`]

    constexpr rep count() const;

__returns `rep_`.

[endsect]
[section:duration_operator_p Member Function `operator+() const`]

    constexpr __duration operator+() const;

__returns `*this`.

[endsect]
[section:duration_operator_m Member Function `operator-() const`]

    constexpr __duration operator-() const;

__returns `__duration(-rep_)`.

[endsect]
[section:duration_operator_pp Member Function `operator++()`]

    __duration& operator++();

__effects  `++rep_`.

__returns `*this`.

[endsect]
[section:duration_operator_pp2 Member Function `operator++(int)`]

    __duration operator++(int);

__returns `__duration(rep_++)`.

[endsect]
[section:duration_operator_mm Member Function `operator--()`]

    __duration& operator--();

__effects  `--rep_`.

__returns `*this`.

[endsect]
[section:duration_operator_mm2 Member Function `operator--(int)`]

    __duration operator--(int);

__returns `__duration(rep_--)`.

[endsect]
[section:duration_operator_pa Member Function `operator+=(const duration&)`]

    __duration& operator+=(const __duration& d);

__effects  `rep_ += d.count()`.

__returns `*this`.

[endsect]
[section:duration_operator_ma Member Function `operator-=(const duration&)`]

    __duration& operator-=(const __duration& d);

__effects  `rep_ -= d.count()`.

__returns `*this`.

[endsect]
[section:duration_operator_moda Member Function `operator%=(const duration&)`]

    __duration& operator%=(const __duration& d);

__effects  `rep_ %= d.count()`.

__returns `*this`.

[endsect]
[section:duration_operator_proda Member Function `operator*=(const rep&)`]

    __duration& operator*=(const rep& rhs);

__effects  `rep_ *= rhs`.

__returns `*this`.

[endsect]
[section:duration_operator_da Member Function `operator/=(const rep&)`]

    __duration& operator/=(const rep& rhs);

__effects  `rep_ /= rhs`.

__returns `*this`.

[endsect]
[section:duration_operator_moda_2 Member Function `operator%=(const rep&)`]

    __duration& operator%=(const rep& rhs);

__effects  `rep_ %= rhs`.

__returns `*this`.

[endsect]


[section:duration_zero Static Member Function `zero()`]

    static constexpr __duration zero();

__returns `__duration(__duration_values<rep>::zero())`.

[endsect]
[section:duration_min Static Member Function `min()`]

    static constexpr __duration min();

__returns `__duration(__duration_values<rep>::min()).`

[endsect]
[section:duration_max Static Member Function `max()`]

    static constexpr __duration max();

__returns `__duration(__duration_values<rep>::max())`.

[endsect]

[endsect]


[section `duration` Non-Member Arithmetic]

[section:duration_operator_p_1 Non-Member Function `operator+(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    typename __common_type<__duration<Rep1, Period1>, __duration<Rep2, Period2> >::type
    operator+(const __duration<Rep1, Period1>& lhs, const __duration<Rep2, Period2>& rhs);

__returns `CD(lhs) += rhs` where `CD` is the type of the return value.

[endsect]
[section:duration_operator_m_1 Non-Member Function `operator-(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    typename __common_type<__duration<Rep1, Period1>, __duration<Rep2, Period2> >::type
    operator-(const __duration<Rep1, Period1>& lhs, const __duration<Rep2, Period2>& rhs);

__returns `CD(lhs) -= rhs` where `CD` is the type of the return value.

    template <class Rep1, class Period, class Rep2>
    __duration<typename __common_type<Rep1, Rep2>::type, Period>
    operator*(const __duration<Rep1, Period>& d, const Rep2& s);

__requires Let `CR` represent the __common_type of `Rep1` and `Rep2`. This function will not participate in overload resolution unless both `Rep1` and `Rep2` are implicitly convertible to `CR`.

__returns `__duration<CR, Period>(d) *= s`.

[endsect]
[section:duration_operator_prod_1 Non-Member Function `operator*(Rep1,duration)`]

    template <class Rep1, class Period, class Rep2>
    __duration<typename __common_type<Rep1, Rep2>::type, Period>
    operator*(const Rep1& s, const __duration<Rep2, Period>& d);

__requires Let `CR` represent the __common_type of `Rep1` and `Rep2`. This function will not participate in overload resolution unless both `Rep1` and `Rep2` are implicitly convertible to `CR`.

__returns `d * s`.

[endsect]
[section:duration_operator_d_1 Non-Member Function `operator/(duration,Rep2)`]

    template <class Rep1, class Period, class Rep2>
    __duration<typename __common_type<Rep1, Rep2>::type, Period>
    operator/(const __duration<Rep1, Period>& d, const Rep2& s);

__requires Let `CR` represent the __common_type of `Rep1` and `Rep2`. This function will not participate in overload resolution unless both `Rep1` and `Rep2` are implicitly convertible to `CR`, and `Rep2` is  not an instantiation of __duration.

__returns `__duration<CR, Period>(d) /= s`.

[endsect]
[section:duration_operator_d_2 Non-Member Function `operator/(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    typename __common_type<Rep1, Rep2>::type
    operator/(const __duration<Rep1, Period1>& lhs, const __duration<Rep2, Period2>& rhs);

__returns Let `CD` represent the __common_type of the two __duration arguments. Returns `CD(lhs).count() / CD(rhs).count()`.

[endsect]

[section:duration_operator_d_3 Non-Member Function `operator/(Rep1,duration)`]

Included only if BOOST_CHRONO_EXTENSIONS is defined.

This overloading could be used to get the frequency of an event counted by `Rep1`.

    template <class Rep1, class Rep2, class Period>
    double operator/(const Rep1& s, const __duration<Rep2, Period>& d);

__remarks Let `CR` represent the __common_type of `Rep1` and `Rep2`. This function will not participate in overload resolution unless both `Rep1` and `Rep2` are implicitly convertible to `CR`, and `Rep1` is  not an instantiation of __duration.

__returns `CR(s)/__duration<CR, Period>(d).count()`.

[endsect]


[section:duration_operator_mod_1 Non-Member Function `operator%(duration,Rep2)`]

  template <class Rep1, class Period, class Rep2>
  __duration<typename __common_type<Rep1, Rep2>::type, Period>
  operator%(const __duration<Rep1, Period>& d, const Rep2& s);

[*Remarks] This function will not participate in overload resolution unless Rep2 must be implicitly convertible to CR(Rep1, Rep2) and Rep2 must not be an instantiation of __duration.

__returns __duration<CR(Rep1,Rep2), Period>(d) %= s.
[endsect]

[section:duration_operator_mod_2 Non-Member Function `operator%(duration,duration)`]

  template <class Rep1, class Period1, class Rep2, class Period2>
  typename __common_type<__duration<Rep1, Period1>, __duration<Rep2, Period2> >::type
  operator%(const __duration<Rep1, Period1>& lhs,
            const __duration<Rep2, Period2>& rhs);

[*Remarks] This function will not participate in overload resolution unless

__returns CD(lhs) %= CD(rhs)

[endsect]
[endsect]

[section `duration` Non-Member Comparaisons]

[section:duration_operator_eq_1 Non-Member Function `operator==(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    bool operator==(const __duration<Rep1, Period1>& lhs,
                    const __duration<Rep2, Period2>& rhs);

__returns Let `CD` represent the __common_type of the two __duration arguments. Returns `CD(lhs).count() == CD(rhs).count()`

[endsect]
[section:duration_operator_neq_1 Non-Member Function `operator!=(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    bool operator!=(const __duration<Rep1, Period1>& lhs,
                    const __duration<Rep2, Period2>& rhs);

__returns `!(lhs == rhs)`.

[endsect]
[section:duration_operator_lt_1 Non-Member Function `operator<(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    bool operator< (const __duration<Rep1, Period1>& lhs,
                    const __duration<Rep2, Period2>& rhs);

__returns Let `CD` represent the __common_type of the two __duration arguments. Returns `CD(lhs).count() < CD(rhs).count()`

[endsect]
[section:duration_operator_leq_1 Non-Member Function `operator<=(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    bool operator<=(const __duration<Rep1, Period1>& lhs,
                    const __duration<Rep2, Period2>& rhs);

__returns `!(rhs < lhs)`.

[endsect]
[section:duration_operator_gt_1 Non-Member Function `operator>(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    bool operator> (const __duration<Rep1, Period1>& lhs,
                    const __duration<Rep2, Period2>& rhs);

__returns `rhs < lhs`.

[endsect]
[section:duration_operator_gteq_1 Non-Member Function `operator>=(duration,duration)`]

    template <class Rep1, class Period1, class Rep2, class Period2>
    bool operator>=(const __duration<Rep1, Period1>& lhs,
                    const __duration<Rep2, Period2>& rhs);

__returns `!(lhs < rhs)`.

[endsect]
[endsect]
[section:duration_cast Non-Member Function `duration_cast(duration)`]

    template <class ToDuration, class Rep, class Period>
    ToDuration duration_cast(const __duration<Rep, Period>& d);

__requires This function will not participate in overload resolution unless `ToDuration` is an instantiation of __duration.

__returns Forms `CF` which is a __ratio resulting from `ratio_divide<Period, typename ToDuration::period>::type`. Let `CR` be the __common_type of `ToDuration::rep`, `Rep`, and `intmax_t`.

* If `CF::num == 1` and `CF::den == 1`, then returns `ToDuration(static_cast<typename ToDuration::rep>(d.count())) `
* else if `CF::num != 1` and `CF::den == 1`, then returns
              `ToDuration(static_cast<typename ToDuration::rep>(static_cast<CR>(d.count()) *
                                                               static_cast<CR>(CF::num)))`
* else if `CF::num == 1` and `CF::den != 1`, then returns
              `ToDuration(static_cast<typename ToDuration::rep>(static_cast<CR>(d.count()) /
                                                               static_cast<CR>(CF::den)))`
* else returns
              `ToDuration(static_cast<typename ToDuration::rep>(static_cast<CR>(d.count()) *
                                                               static_cast<CR>(CF::num)   /
                                                               static_cast<CR>(CF::den)))`

__remarks This function does not rely on any implicit conversions. All conversions must be accomplished through `static_cast`. The implementation avoids all multiplications or divisions when it is known at compile-time that it can be avoided because one or more arguments are `1`. All intermediate computations are carried out in the widest possible representation and only converted to the destination representation at the final step.


[endsect]


[section:duration_typedefs `duration` typedefs]

        // convenience typedefs
        typedef __duration<boost::int_least64_t, nano> nanoseconds;    // at least 64 bits needed
        typedef __duration<boost::int_least64_t, micro> microseconds;  // at least 55 bits needed
        typedef __duration<boost::int_least64_t, milli> milliseconds;  // at least 45 bits needed
        typedef __duration<boost::int_least64_t> seconds;              // at least 35 bits needed
        typedef __duration<boost::int_least32_t, __ratio< 60> > minutes; // at least 29 bits needed
        typedef __duration<boost::int_least32_t, __ratio<3600> > hours;  // at least 23 bits needed

[endsect]

[endsect]

[section:clock `Clock` Requirements]

A clock represents a bundle consisting of a  __duration, a  __time_point, and a function `now()` to get the current __time_point. A clock must meet the requirements in the following Table.

In this table `C1` and `C2` denote `clock` types. `t1` and `t2` are values returned from `C1::now()` where the call returning `t1` happens before the call returning `t2` and both of these calls happen before `C1::time_point::max()`.

[table Clock Requirements
    [[expression]        [return type]  [operational semantics]]
    [[`C1::rep`]        [An arithmetic type or class emulating an arithmetic type. ]  [The representation type of the  __duration and __time_point.]]
    [[`C1::period`]        [`ratio`]  [The tick period of the clock in seconds.]]
    [[`C1::duration`]        [`chrono::duration<C1::rep, C1::period>`]  [The  __duration type of the `clock`.]]
    [[`C1::time_point`]        [`chrono::time_point<C1> or chrono::time_point<C2, C1::duration>`]  [The  __time_point type of the `clock`. Different clocks are permitted to share a __time_point definition if it is valid to compare their time_points by comparing their respective __durations. `C1` and `C2` must refer to the same epoch.]]
    [[`C1::is_steady`]        [`constexpr bool`]  [`true` if `t1 <= t2` is always `true`, else `false`. *Note*: A `clock` that can be adjusted backwards is not steady]]
    [[`C1::now()`]        [`C1::time_point`]  [Returns a __time_point representing the current point in time.]]
]


Models of Clock:

* __system_clock
* __steady_clock
* __high_resolution_clock
* __process_real_cpu_clock
* __process_user_cpu_clock
* __process_system_cpu_clock
* __thread_clock

[endsect]

[/=============================================]
[section:time_point_hpp Header `<boost/chrono/time_point.hpp>`]
[/=============================================]

This file contains __time_point specific classes and non-member functions.

    namespace boost {
      namespace chrono {

        template <class Clock, class Duration = typename Clock::duration> class __time_point;

      }
      template <class Clock, class Duration1, class Duration2>
      struct __common_type_spe<time_point<Clock, Duration1>,
                         time_point<Clock, Duration2> >;

      namespace chrono {

        // time_point arithmetic
        template <class Clock, class Duration1, class Rep2, class Period2>
        time_point<Clock, typename common_type<Duration1, duration<Rep2, Period2> >::type>
        operator+(const time_point<Clock, Duration1>& lhs, const duration<Rep2, Period2>& rhs);

        template <class Rep1, class Period1, class Clock, class Duration2>
        time_point<Clock, typename common_type<duration<Rep1, Period1>, Duration2>::type>
        operator+(const duration<Rep1, Period1>& lhs, const time_point<Clock, Duration2>& rhs);

        template <class Clock, class Duration1, class Rep2, class Period2>
        time_point<Clock, typename common_type<Duration1, duration<Rep2, Period2> >::type>
        operator-(const time_point<Clock, Duration1>& lhs, const duration<Rep2, Period2>& rhs);

        template <class Clock, class Duration1, class Duration2>
        typename common_type<Duration1, Duration2>::type
        operator-(const time_point<Clock, Duration1>& lhs, const time_point<Clock,
                Duration2>& rhs);

        // time_point comparisons
        template <class Clock, class Duration1, class Duration2>
        constexpr bool operator==(const time_point<Clock, Duration1>& lhs,
                        const time_point<Clock, Duration2>& rhs);
        template <class Clock, class Duration1, class Duration2>
        constexpr bool operator!=(const time_point<Clock, Duration1>& lhs,
                        const time_point<Clock, Duration2>& rhs);
        template <class Clock, class Duration1, class Duration2>
        constexpr bool operator< (const time_point<Clock, Duration1>& lhs,
                        const time_point<Clock, Duration2>& rhs);
        template <class Clock, class Duration1, class Duration2>
        constexpr bool operator<=(const time_point<Clock, Duration1>& lhs,
                        const time_point<Clock, Duration2>& rhs);
        template <class Clock, class Duration1, class Duration2>
        constexpr bool operator> (const time_point<Clock, Duration1>& lhs,
                        const time_point<Clock, Duration2>& rhs);
        template <class Clock, class Duration1, class Duration2>
        constexpr bool operator>=(const time_point<Clock, Duration1>& lhs,
                        const time_point<Clock, Duration2>& rhs);

        // time_point_cast
        template <class ToDuration, class Clock, class Duration>
        constexpr time_point<Clock, ToDuration> __time_point_cast(const time_point<Clock, Duration>& t);

      }
    }


[section:common_type_spe2 `common_type` specialization]

    template <class Clock, class Duration1, class Duration2>
    struct __common_type<chrono::__time_point<Clock, Duration1>, chrono::__time_point<Clock, Duration2> >
    {
        typedef chrono::__time_point<Clock, typename __common_type<Duration1, Duration2>::type> type;
    };

The __common_type of two __time_points is a __time_point with the same `clock` (both have the same `clock`), and the __common_type of the two __durations.

[endsect]

[section:time_point Class template `time_point<>`]

A __time_point represents a point in time with respect to a specific clock.

    template <class Clock, class Duration>
    class time_point {
    public:
        typedef Clock                     clock;
        typedef Duration                  duration;
        typedef typename duration::rep    rep;
        typedef typename duration::period period;
    private:
        duration d_; // exposition only
    public:
        constexpr time_point();
        constexpr explicit time_point(const duration& d);

        // conversions
        template <class Duration2>
        time_point(const time_point<clock, Duration2>& t);

        // observer

        constexpr duration time_since_epoch() const;

        // arithmetic

        #ifdef BOOST_CHRONO_EXTENSIONS      
        constexpr time_point  operator+();
        constexpr time_point  operator-();
        time_point& operator++();
        time_point  operator++(int);
        time_point& operator--();
        time_point  operator--(int);

        time_point& operator+=(const rep& d);
        time_point& operator-=(const rep& d);
        #endif

        time_point& operator+=(const duration& d);
        time_point& operator-=(const duration& d);

        // special values

        static constexpr time_point min();
        static constexpr time_point max();
    };

Clock must meet the __clock_req.

Duration must be an instantiation of __duration, compile diagnostic otherwise.

[section:time_point_c_1 Constructor `time_point()`]

    constexpr time_point();

__effects  Constructs an object of __time_point, initializing `d_` with `duration::zero()`. This __time_point represents the epoch.

[endsect]
[section:time_point_c_2 Constructor `time_point(const duration&)`]

    constexpr time_point(const duration& d);

__effects  Constructs an object of __time_point, initializing `d_` with `d`. This __time_point represents the epoch `+ d`.

[endsect]
[section:time_point_c_3 Copy Constructor `time_point(const time_point&)`]

    template <class Duration2> time_point(const __time_point<clock, Duration2>& t);

__requires This function will not participate in overload resolution unless `Duration2` is implicitly convertible to __duration.

__effects  Constructs an object of __time_point, initializing `d_` with `t.time_since_epoch()`.

[endsect]

[section:time_since_epoch Member Function `time_since_epoch() const`]

    constexpr duration time_since_epoch() const;

__returns `d_`.

[endsect]

[section:operator_p Member Function `operator+() const`]

    constexpr __time_point operator+() const;

__returns `*this`.

[endsect]
[section:operator_m Member Function `operator-() const`]

    constexpr __time_point operator-() const;

__returns `__time_point(-d_)`.

[endsect]
[section:operator_pp Member Function `operator++()`]

    __time_point& operator++();

__effects  `++d_`.

__returns `*this`.

[endsect]
[section:operator_pp2 Member Function `operator++(int)`]

    __time_point operator++(int);

__returns `__time_point(d_++)`.

[endsect]
[section:operator_mm Member Function `operator--()`]

    __time_point& operator--();

__effects  `--d_`.

__returns `*this`.

[endsect]
[section:operator_mm2 Member Function `operator--(int)`]

    __time_point operator--(int);

__returns `__time_point(d_--)`.

[endsect]

[section:time_point_operator_per Member Function `operator+=`]

    __time_point& operator+=(const rep& r);

__effects  `d_ += duration(r)`.

__returns `*this`.

[endsect]
[section:time_point_operator_mer Member Function `operator-=`]

    __time_point& operator-=(const rep& r);

__effects  `d_ -= duration(r)`

__returns `*this`.

[endsect]


[section:time_point_operator_pe Member Function `operator+=`]

    time_point& operator+=(const duration& d);

__effects  `d_ += d`.

__returns `*this`.

[endsect]
[section:time_point_operator_me Member Function `operator-=`]

    time_point& operator-=(const duration& d);

__effects  `d_ -= d`

__returns `*this`.

[endsect]
[section:time_point_min Static Member Function `min`]

    static constexpr time_point min();

__returns `time_point(duration::min())`.

[endsect]
[section:time_point_max Static Member Function `max`]

    static constexpr time_point max();

__returns `time_point(duration::max())`.

[endsect]
[endsect]


[section `time_point` non-member arithmetic]


[section:time_point_operator_p_1 Non-Member Function `operator+(time_point,duration)`]

    template <class Clock, class Duration1, class Rep2, class Period2>
    __time_point<Clock, typename __common_type<Duration1, duration<Rep2, Period2> >::type>
    operator+(const __time_point<Clock, Duration1>& lhs,
              const duration<Rep2, Period2>& rhs);

__returns `CT(lhs) += rhs` where `CT` is the type of the return value.

[endsect]
[section:time_point_operator_p_2 Non-Member Function `operator+(duration,time_point)`]

    template <class Rep1, class Period1, class Clock, class Duration2>
    __time_point<Clock, typename __common_type<duration<Rep1, Period1>, Duration2>::type>
    operator+(const duration<Rep1, Period1>& lhs,
              const __time_point<Clock, Duration2>& rhs);

__returns `rhs + lhs`.

[endsect]
[section:time_point_operator_m_1 Non-Member Function `operator-(time_point,duration)`]

    template <class Clock, class Duration1, class Rep2, class Period2>
    __time_point<Clock, typename __common_type<Duration1, duration<Rep2, Period2> >::type>
    operator-(const __time_point<Clock, Duration1>& lhs,
              const duration<Rep2, Period2>& rhs);

__returns `lhs + (-rhs)`.

[endsect]
[section:time_point_operator_m_2 Non-Member Function `operator-(time_point,time_point)`]

    template <class Clock, class Duration1, class Duration2>
    typename __common_type<Duration1, Duration2>::type
    operator-(const __time_point<Clock, Duration1>& lhs,
              const __time_point<Clock, Duration2>& rhs);

__returns `lhs.time_since_epoch() - rhs.time_since_epoch()`.

[endsect]
[endsect]

[section `time_point` non-member comparisons]
[section:time_point_operator_eq Non-Member Function `operator==(time_point,time_point)`]

    template <class Clock, class Duration1, class Duration2>
    bool operator==(const __time_point<Clock, Duration1>& lhs,
                    const __time_point<Clock, Duration2>& rhs);

__returns `lhs.time_since_epoch() == rhs.time_since_epoch()`.

[endsect]
[section:time_point_operator_neq Non-Member Function `operator!=(time_point,time_point)`]

template <class Clock, class Duration1, class Duration2>
   bool operator!=(const __time_point<Clock, Duration1>& lhs,
                   const __time_point<Clock, Duration2>& rhs);

__returns `!(lhs == rhs)`.

[endsect]
[section:time_point_operator_lt Non-Member Function `operator<(time_point,time_point)`]

    template <class Clock, class Duration1, class Duration2>
    bool operator< (const __time_point<Clock, Duration1>& lhs,
                    const __time_point<Clock, Duration2>& rhs);

__returns lhs.time_since_epoch() < rhs.time_since_epoch().

[endsect]
[section:time_point_operator_leq Non-Member Function `operator<=(time_point,time_point)`]

    template <class Clock, class Duration1, class Duration2>
    bool operator<=(const __time_point<Clock, Duration1>& lhs,
                    const __time_point<Clock, Duration2>& rhs);

__returns `!(rhs < lhs)`.

[endsect]
[section:time_point_operator_gt Non-Member Function `operator>(time_point,time_point)`]

template <class Clock, class Duration1, class Duration2>
   bool operator>(const __time_point<Clock, Duration1>& lhs,
                  const __time_point<Clock, Duration2>& rhs);

__returns `rhs < lhs`.

[endsect]
[section:time_point_operator_geq Non-Member Function `operator>=(time_point,time_point)`]

    template <class Clock, class Duration1, class Duration2>
    bool operator>=(const __time_point<Clock, Duration1>& lhs,
                    const __time_point<Clock, Duration2>& rhs);

__returns `!(lhs < rhs)`.

[endsect]
[endsect]


[section:time_point_cast Non-Member Function `time_point_cast(time_point)`]

    template <class ToDuration, class Clock, class Duration>
    __time_point<Clock, ToDuration> __time_point_cast(const __time_point<Clock, Duration>& t);

__requires This function will not participate in overload resolution unless `ToDuration` is an instantiation of __duration.

__returns `__time_point<Clock, ToDuration>(__duration_cast<ToDuration>(t.time_since_epoch()))`.

[endsect]

[endsect]

[/=============================================]
[section:system_clocks_hpp Header `<boost/chrono/system_clocks.hpp>`]
[/=============================================]

This file contains the standard clock classes.

    namespace boost {
      namespace chrono {

        // Clocks
        class __system_clock;
        class __steady_clock;
        class __high_resolution_clock;

      }
    }


[section:system_clock Class `system_clock`]

The __system_clock class provides a means of obtaining the current wall-clock time from the system-wide real-time clock. The current time can be obtained by calling `system_clock::now()`. Instances of `system_clock::time_point`  can be converted to and from time_t  with the `system_clock::to_time_t()`  and `system_clock::to_time_point()`  functions. If system clock is not steady, a subsequent call to `system_clock::now()`  may return an earlier time than a previous call (e.g. if the operating system clock is manually adjusted, or synchronized with an external clock).

The current implementation of __system_clock is related an epoch (midnight UTC of January 1, 1970), but this is not in the contract. You need to use the static function static

    std::time_t to_time_t(const time_point& t);

which returns a `time_t` type that is based on midnight UTC of January 1, 1970.

    class system_clock {
    public:
        typedef __see_bellow__          duration;
        typedef duration::rep                        rep;
        typedef duration::period                     period;
        typedef chrono::__time_point<system_clock>     time_point;
        static constexpr bool is_steady =            false;

        static time_point  now();                         // throws on error
        static time_point  now(system::error_code & ec);  // never throws

        // Map to C API
        static std::time_t to_time_t(const time_point& t);
        static time_point  from_time_t(std::time_t t);
    };

__system_clock satisfy the __clock_req:

* `system_clock::duration::min() < system_clock::duration::zero()` is `true`.

* The nested duration typedef has a resolution that depends on the one provided by the platform.

[section:to_time_t Static Member Function `to_time_t(time_point)`]

time_t to_time_t(const time_point& t);

__returns A `time_t` such that the `time_t` and `t` represent the same point in time, truncated to the courser of the precisions among `time_t` and `t`.

[endsect]
[section:from_time_t Static Member Function `from_time_t(time_t)`]

    time_point from_time_t(time_t t);

__returns A __time_point such that the __time_point and `t` represent the same point in time, truncated to the coarser of the precisions among __time_point and `t`.

[endsect]
[endsect]

[section:BOOST_CHRONO_HAS_CLOCK_STEADY Macro `BOOST_CHRONO_HAS_CLOCK_STEADY`]

Defined if the platform support steady clocks.

[endsect]

[section:steady_clock Class `steady_clock`]

__steady_clock satisfy the __clock_req.

__steady_clock class provides access to the system-wide steady clock. The current time can be obtained by calling `steady_clock::now()`. There is no fixed relationship between values returned by `steady_clock::now()` and wall-clock time.

    #ifdef BOOST_HAS_CLOCK_STEADY
        class steady_clock {
        public:
            typedef __nanoseconds                          duration;
            typedef duration::rep                        rep;
            typedef duration::period                     period;
            typedef chrono::__time_point<steady_clock>  time_point;
            static constexpr bool is_steady =            true;

            static time_point  now();                         // throws on error
            static time_point  now(system::error_code & ec);  // never throws
        };
    #endif



[endsect]

[section:high_resolution_clock Class `high_resolution_clock`]

__high_resolution_clock satisfy the __clock_req.

    #ifdef __BOOST_CHRONO_HAS_CLOCK_STEADY
      typedef __steady_clock high_resolution_clock;  // as permitted by [time.clock.hires]
    #else
      typedef __system_clock high_resolution_clock;  // as permitted by [time.clock.hires]
    #endif

[endsect]

[endsect]

[/=============================================]
[section:chrono_typeof_hpp Header `<boost/chrono/typeof/boost/chrono/chrono.hpp>`]
[/=============================================]

Register __duration`<>` and __time_point`<>` class templates to [*Boost.Typeof].

[endsect]
[endsect]

[section:io Chrono I/O]
[/==================================================================]
[section:chrono_io_hpp Header `<boost/chrono/chrono_io.hpp>`]
[/==================================================================]


[/The current implementation makes use of a few utilities in libc++ as `__scan_keyword` which has also been ported and seen as implementation details.]


    namespace boost {
    namespace chrono {

        template <class CharT>
        class duration_punct;

        template <class Clock, class CharT>
        struct clock_string;

        template <class CharT, class Traits>
            std::basic_ostream<CharT, Traits>&
            duration_short(std::basic_ostream<CharT, Traits>& os);

        template <class CharT, class Traits>
            std::basic_ostream<CharT, Traits>&
            duration_long(std::basic_ostream<CharT, Traits>& os);

        template <class CharT, class Traits, class Rep, class Period>
            std::basic_ostream<CharT, Traits>&
            operator<<(std::basic_ostream<CharT, Traits>& os, const duration<Rep, Period>& d);

        template <class CharT, class Traits, class Rep, class Period>
            std::basic_istream<CharT, Traits>&
            operator>>(std::basic_istream<CharT, Traits>& is, duration<Rep, Period>& d)

        template <class CharT, class Traits, class Clock, class Duration>
            std::basic_ostream<CharT, Traits>&
            operator<<(std::basic_ostream<CharT, Traits>& os,
                   const time_point<Clock, Duration>& tp);

        template <class CharT, class Traits, class Clock, class Duration>
            std::basic_istream<CharT, Traits>&
            operator>>(std::basic_istream<CharT, Traits>& is,
                   time_point<Clock, Duration>& tp);

    }
    }

[section:duration_punct Template Class `duration_punct<>`]

The __duration unit names can be customized through the facet: __duration_punct. __duration unit names come in two varieties: long and short. The default constructed __duration_punct provides names in the long format. These names are English descriptions. Other languages are supported by constructing a __duration_punct with the proper spellings for "hours", "minutes" and "seconds", and their abbreviations (for the short format).

        template <class CharT>
        class duration_punct
            : public std::locale::facet
        {
        public:
            typedef std::basic_string<CharT> string_type;
            enum {use_long, use_short};

            static std::locale::id id;

            explicit duration_punct(int use = use_long);

            duration_punct(int use,
                const string_type& long_seconds, const string_type& long_minutes,
                const string_type& long_hours, const string_type& short_seconds,
                const string_type& short_minutes, const string_type& short_hours);

            duration_punct(int use, const duration_punct& d);

            template <class Period> string_type short_name() const;
            template <class Period> string_type long_name() const;
            template <class Period> string_type name() const;

            bool is_short_name() const;
            bool is_long_name() const;
        };

[endsect]

[section:clock_string Template Class `clock_string<>`]

    template <class Clock, class CharT>
    struct clock_string;

This template must be specialized for specific clocks. The specialization must define the following functions

        static std::basic_string<CharT> name();
        static std::basic_string<CharT> since();

`clock_string<>::name()` return the clock name, which usually corresponds to the class name.
`clock_string<>::since()` return the textual format of the clock epoch.


[endsect]

[section:clock_string_system_clock `clock_string<system_clock>` Specialization]

    template <class CharT>
    struct clock_string<system_clock, CharT>
    {
        static std::basic_string<CharT> name();
        static std::basic_string<CharT> since();
    };

`clock_string<>::name()` returns "system_clock".
`clock_string<>::since()` returns " since Jan 1, 1970"


[endsect]

[section:clock_string_steady_clock `clock_string<steady_clock>` Specialization]

    #ifdef BOOST_CHRONO_HAS_CLOCK_STEADY

    template <class CharT>
    struct clock_string<steady_clock, CharT>
    {
        static std::basic_string<CharT> name();
        static std::basic_string<CharT> since();
    };
    #endif

`clock_string<>::name()` returns "steady_clock".
`clock_string<>::since()` returns " since boot"

[endsect]

[section:clock_string_thread_clock `clock_string<thread_clock>` Specialization]

    #if defined(BOOST_CHRONO_HAS_THREAD_CLOCK)
    template <class CharT>
    struct clock_string<thread_clock, CharT>
    {
        static std::basic_string<CharT> name();
        static std::basic_string<CharT> since();
    };
    #endif

`clock_string<>::name()` returns "thread_clock".
`clock_string<>::since()` returns " since thread start-up"


[endsect]

[section:clock_string_process_real_cpu_clock `clock_string<process_real_cpu_clock>` Specialization]

    template <class CharT>
    struct clock_string<process_real_cpu_clock, CharT>
    {
        static std::basic_string<CharT> name();
        static std::basic_string<CharT> since();
    };

`clock_string<>::name()` returns "process_real_cpu_clock".
`clock_string<>::since()` returns " since process start-up"

[endsect]

[section:clock_string_process_user_cpu_clock `clock_string<process_user_cpu_clock>` Specialization]

    template <class CharT>
    struct clock_string<process_user_cpu_clock, CharT>
    {
        static std::basic_string<CharT> name();
        static std::basic_string<CharT> since();
    };

`clock_string<>::name()` returns "process_user_cpu_clock".
`clock_string<>::since()` returns " since process start-up"


[endsect]

[section:clock_string_process_system_cpu_clock `clock_string<process_system_cpu_clock>` Specialization]

    template <class CharT>
    struct clock_string<process_system_cpu_clock, CharT>
    {
        static std::basic_string<CharT> name();
        static std::basic_string<CharT> since();
    };

`clock_string<>::name()` returns "process_system_cpu_clock".
`clock_string<>::since()` returns " since process start-up"


[endsect]

[section:clock_string_process_cpu_clock `clock_string<process_cpu_clock>` Specialization]

    template <class CharT>
    struct clock_string<process_cpu_clock, CharT>
    {
        static std::basic_string<CharT> name();
        static std::basic_string<CharT> since();
    };

`clock_string<>::name()` returns "process_cpu_clock".
`clock_string<>::since()` returns " since process start-up"


[endsect]

[section:manipulators I/O Manipulators]

The short or long format can be easily chosen by streaming a `duration_short` or `duration_long` manipulator respectively.

        template <class CharT, class Traits>
            std::basic_ostream<CharT, Traits>&
            duration_short(std::basic_ostream<CharT, Traits>& os);

__effects Set the __duration_punct facet to stream __durations and __time_points as abbreviations.

__returns the output stream

        template <class CharT, class Traits>
            std::basic_ostream<CharT, Traits>&
            duration_long(std::basic_ostream<CharT, Traits>& os);


__effects Set the __duration_punct facet to stream durations and time_points as long text.

__returns the output stream


[endsect]

[section:streams I/O Streams Operations]

Any __duration can be streamed out to a `basic_ostream`. The run-time value of the __duration is formatted according to the rules and current format settings for __duration`::rep`. This is followed by a single space and then the compile-time unit name of the __duration. This unit name is built on the string returned from `ratio_string<>` and the data used to construct the __duration_punct which was inserted into the stream's locale. If a __duration_punct has not been inserted into the stream's locale, a default constructed __duration_punct will be added to the stream's locale.

A __time_point is formatted by outputting its internal __duration followed by a string that describes the __time_point`::clock` epoch. This string will vary for each distinct clock, and for each implementation of the supplied clocks.

        template <class CharT, class Traits, class Rep, class Period>
            std::basic_ostream<CharT, Traits>&
            operator<<(std::basic_ostream<CharT, Traits>& os, const duration<Rep, Period>& d);

__effects outputs the __duration as an abrevieated or long text format depending on the state of the __duration_punct facet.

__returns the output stream

        template <class CharT, class Traits, class Rep, class Period>
            std::basic_istream<CharT, Traits>&
            operator>>(std::basic_istream<CharT, Traits>& is, duration<Rep, Period>& d)

__effects reads a __duration from the input stream. If a format error is found, the input stream state will be set to `failbit`.

__returns the  input stream

        template <class CharT, class Traits, class Clock, class Duration>
            std::basic_ostream<CharT, Traits>&
            operator<<(std::basic_ostream<CharT, Traits>& os,
                   const time_point<Clock, Duration>& tp);

__effects outputs the __time_point as an abrevieated or long text format depending on the state of the __duration_punct facet.

__returns the output stream


        template <class CharT, class Traits, class Clock, class Duration>
            std::basic_istream<CharT, Traits>&
            operator>>(std::basic_istream<CharT, Traits>& is,
                   time_point<Clock, Duration>& tp);

__effects reads a __time_point from the input stream. If a format error is found, the input stream state will be set to `failbit`.

__returns the input stream

[endsect]


[endsect]
[endsect]

[section:other_clocks Other Clocks]

[/==================================================================]
[section:process_cpu_clocks_hpp Header `<boost/chrono/process_cpu_clocks.hpp>`]
[/==================================================================]

Knowing how long a program takes to execute is useful in both test and production environments. It is also helpful if such timing information is broken down into real (wall clock) time, CPU time spent by the user, and CPU time spent by the operating system servicing user requests.

Process clocks don't include the time spent by the child process.

    namespace boost { namespace chrono {

        class process_real_cpu_clock;
        class process_user_cpu_clock;
        class process_system_cpu_clock;
        class process_cpu_clock;

        struct process_cpu_clock::times;
        template <class CharT, class Traits>
        std::basic_ostream<CharT, Traits>&
        operator<<(std::basic_ostream<CharT, Traits>& os,
                process_cpu_clock::times const& rhs);

        template <class CharT, class Traits>
        std::basic_istream<CharT, Traits>&
        operator>>(std::basic_istream<CharT, Traits>& is,
                process_cpu_clock::times const& rhs);

        template <>
        struct duration_values<process_cpu_clock::times>;
    } }
    namespace std {
        template <>
        class numeric_limits<boost::chrono::process_cpu_clock::times>;
    }

[section:process_real_cpu_clock Class `process_real_cpu_clock`]

__process_real_cpu_clock satisfy the __clock_req.

__process_real_cpu_clock class provides access to the real process wall-clock steady clock, i.e. the real CPU-time clock of the calling process. The process relative current time can be obtained by calling `process_real_cpu_clock::now()`.

        class process_real_cpu_clock {
        public:
            typedef __nanoseconds                          duration;
            typedef duration::rep                        rep;
            typedef duration::period                     period;
            typedef chrono::__time_point<process_real_cpu_clock>    time_point;
            static constexpr bool is_steady =            true;

            static time_point now( system::error_code & ec = system::throws );
        };


[endsect]
[section:process_user_cpu_clock Class `process_user_cpu_clock`]

__process_user_cpu_clock satisfy the __clock_req.

__process_user_cpu_clock class provides access to the user CPU-time steady clock of the calling process. The process relative user current time can be obtained by calling `process_user_cpu_clock::now()`.

        class process_user_cpu_clock {
        public:
            typedef __nanoseconds                          duration;
            typedef duration::rep                        rep;
            typedef duration::period                     period;
            typedef chrono::__time_point<process_user_cpu_clock>    time_point;
            static constexpr bool is_steady =            true;

            static time_point now( system::error_code & ec = system::throws );
        };


[endsect]

[section:process_system_cpu_clock Class `process_system_cpu_clock`]

__process_system_cpu_clock satisfy the __clock_req.

__process_system_cpu_clock class provides access to the system CPU-time steady clockof the calling process. The process relative system current time can be obtained by calling `process_system_cpu_clock::now()`.

        class process_system_cpu_clock {
        public:
            typedef __nanoseconds                          duration;
            typedef duration::rep                        rep;
            typedef duration::period                     period;
            typedef chrono::__time_point<process_system_cpu_clock>    time_point;
            static constexpr bool is_steady =            true;

            static time_point now( system::error_code & ec = system::throws );
        };


[endsect]

[section:process_cpu_clock Class `process_cpu_clock`]

`process_cpu_clock` can be considered as a `tuple<process_real_cpu_clock, process_user_cpu_clock, process_system_cpu_clock>`.

`process_cpu_clock` provides a thin wrapper around the operating system's process time API. For POSIX-like systems, that's the times() function, while for Windows, it's the `GetProcessTimes()` function.

The process relative real, user and system current time can be obtained at once by calling `process_clocks::now()`.

    class process_cpu_clock
    {
    public:
        struct times ;

        typedef __duration<times,  nano>                  duration;
        typedef duration::rep                           rep;
        typedef duration::period                        period;
        typedef chrono::__time_point<process_cpu_clock>   time_point;
        static constexpr bool is_steady =               true;

        static time_point now( system::error_code & ec = system::throws );
    };

[endsect]

[section:times Class `process_cpu_clock::times`]

This class is the representation of the `process_cpu_clock::duration` class. As such it needs to implements the arithmetic operators.

        struct times : arithmetic<times,
            multiplicative<times, process_real_cpu_clock::rep,
            less_than_comparable<times> > >
        {
            process_real_cpu_clock::rep   real;    // real (i.e wall clock) time
            process_user_cpu_clock::rep   user;    // user cpu time
            process_system_cpu_clock::rep system;  // system cpu time

            times();
            times(
                process_real_cpu_clock::rep r,
                process_user_cpu_clock::rep u,
                process_system_cpu_clock::rep s);

            bool operator==(times const& rhs);

            times operator+=(times const& rhs);
            times operator-=(times const& rhs);
            times operator*=(times const& rhs);
            times operator/=(times const& rhs);
            bool operator<(times const & rhs) const;
        };

[endsect]

[section:times_io `process_cpu_clock::times` Input/Output]

    template <class CharT, class Traits>
    std::basic_ostream<CharT, Traits>&
    operator<<(std::basic_ostream<CharT, Traits>& os,
            process_cpu_clock::times const& rhs);

[*Effect]: Output each part separated by ';' and sourrounded by '{', '}'.
[*Throws]: None.

    template <class CharT, class Traits>
    std::basic_istream<CharT, Traits>&
    operator>>(std::basic_istream<CharT, Traits>& is,
            process_cpu_clock::times const& rhs);

[*Effect]: overrides the value of rhs if the input stream has the format "{r;u;s}". Otherwise, set the input stream state as failbit | eofbit.
[*Throws]: None.


[endsect]

[section:times_duration_values `duration_values` Specialization for `times`]

    template <>
    struct __duration_values<process_cpu_clock::times>
    {
        static process_cpu_clock::times zero();
        static process_cpu_clock::times max();
        static process_cpu_clock::times min();
    };

The `times` specific functions `zero()`, `max()` and `min()` uses the relative functions on the representation of each component.

[endsect]

[section:times_numeric_limits `numeric_limits` Specialization for `times`]

    namespace std {
        template <>
        class numeric_limits<boost::chrono::process_cpu_clock::times> {
            typedef boost::chrono::process_cpu_clock::times Rep;

        public:
            static const bool is_specialized = true;
            static Rep min();
            static Rep max();
            static Rep lowest();
            static const int digits;
            static const int digits10;
            static const bool is_signed = false;
            static const bool is_integer = true;
            static const bool is_exact = true;
            static const int radix = 0;
        };
    }

The `times` specialization functions `min()`, `max()` and `lowest()` uses the relative functions on the representation of each component.

Notes

* `min()` returns the tuple of mins.
* `max()` returns the tuple of maxs.
* `lowest()` returns the tuple of lowests.
* `digits` is the sum of (binary) digits.
* `digits10` is the sum of digits10s.

[endsect]

[endsect]

[/==================================================================]
[section:thread_clock_hpp Header `<boost/chrono/thread_clock.hpp>`]
[/==================================================================]

Knowing the time a thread takes to execute is useful in both test and production environments.

    #define BOOST_CHRONO_HAS_THREAD_CLOCK
    #define BOOST_CHRONO_THREAD_CLOCK_IS_STEADY
    namespace boost { namespace chrono {

        class thread_clock;

    } }

[section:BOOST_CHRONO_HAS_THREAD_CLOCK Macro `BOOST_CHRONO_HAS_THREAD_CLOCK`]

This macro is defined if the platform supports thread clocks.

[endsect]

[section:BOOST_CHRONO_THREAD_CLOCK_IS_STEADY Macro `BOOST_CHRONO_THREAD_CLOCK_IS_STEADY`]

This macro is defined if the platform has a thread clock. Its value is true if it is steady and false otherwise.

[endsect]

[section:thread_clock Class `thread_clock`]

__thread_clock satisfy the __clock_req.

__thread_clock class provides access to the real thread wall-clock, i.e. the real CPU-time clock of the calling thread. The thread relative current time can be obtained by calling `thread_clock::now()`.

        class thread_clock {
        public:
            typedef __nanoseconds                          duration;
            typedef duration::rep                        rep;
            typedef duration::period                     period;
            typedef chrono::__time_point<thread_clock>     time_point;
            static constexpr bool is_steady =            BOOST_CHRONO_THREAD_CLOCK_IS_STEADY;

            static time_point now( system::error_code & ec = system::throws );
        };


[endsect]

[endsect]



[endsect]

[/
[section:deprecated Deprecated Headers]

See Boost.Stopwatches for similar functionality.

[/==================================================]
[section:timer_hpp Deprecated Header `<boost/chrono/timer.hpp>`]
[/==================================================]

This header has been deprecated, use instead <boost/chrono/stopwatch.hpp>.

    namespace boost { namespace chrono  {
        template <class Clock=high_resolution_clock> class timer;
        typedef <see above> system_timer;
        #ifdef __BOOST_CHRONO_HAS_CLOCK_STEADY
        typedef <see above> steady_timer;
        #endif
        typedef <see above> high_resolution_timer;
    }}

[/
        typedef <see above> process_real_cpu_timer;
        typedef <see above> process_user_cpu_timer;
        typedef <see above> process_system_cpu_timer;
]
[section:timer Template Class `timer<>`]

Knowing how long a part of a program takes to execute is useful in both test and production environments.
A `timer` object measures elapsed time. It is recommended to use it with clocks that measure wall clock rather than CPU time since the intended use is performance measurement on systems where total elapsed time is more important than just process or CPU time.

The maximum measurable elapsed time depends on the Clock parameter. The accuracy of timings depends on the
accuracy of timing information provided the Clock, and this coudl varies a great deal from one clock to another.

        template <class Clock> class timer {
        public:
            typedef Clock                       clock;
            typedef typename Clock::duration    duration;
            typedef typename Clock::time_point  time_point;

            explicit timer( system::error_code & ec = system::throws );

            ~timer();

            void start( system::error_code & ec = system::throws );
            duration elapsed( system::error_code & ec = system::throws );

        };

[endsect]

[section:timer_typedefs `timer` useful typedefs]

        typedef boost::chrono::timer< boost::chrono::system_clock >
            system_timer;
        #ifdef __BOOST_CHRONO_HAS_CLOCK_STEADY
        typedef boost::chrono::timer< boost::chrono::steady_clock >
            steady_timer;
        #endif
        typedef boost::chrono::timer< boost::chrono::high_resolution_clock >
            high_resolution_timer;

[/
        typedef boost::chrono::timer< boost::chrono::process_real_cpu_clock > process_real_cpu_timer;
        typedef boost::chrono::timer< boost::chrono::process_user_cpu_clock > process_user_cpu_timer;
        typedef boost::chrono::timer< boost::chrono::process_system_cpu_clock > process_system_cpu_timer;
]
[endsect]
[endsect]


[/==================================================================]
[section:process_times_hpp Deprecated Header `<boost/chrono/process_times.hpp>`]
[/==================================================================]

This header has been deprecated. Use instead `<boost/chrono/process_cpu_clocks.hpp>`, `<boost/chrono/stopwatch.hpp>`, `<boost/chrono/stopwatch_reporter.hpp>` and `<boost/chrono/stopclock.hpp>` files.

    namespace boost { namespace chrono {

        class process_clock;
        typedef <see below> process_times;
        class process_timer;
        class run_timer;

    } }

[section:process_clock Class `process_clock`]

`process_clock` doesn't satisfy the Clock Requirements as the function now do not follows the Clock prototype.

`process_clock` provides a thin wrapper around the operating system's process time API. For POSIX-like systems, that's the times() function, while for Windows, it's the GetProcessTimes() function.

The process relative real, user and system current time can be obtained at once by calling `process_clock::now()`.


        class process_clock {
        public:
            typedef __nanoseconds                          duration;
            typedef duration::rep                        rep;
            typedef duration::period                     period;
            typedef chrono::__time_point<process_clock>    time_point;
            static constexpr bool is_steady =            true;

            struct process_times;
            static void now( process_times & times,
                             system::error_code & ec = system::throws );
        };

[section:process_times Class `process_times`]

        struct process_times {
            process_clock::duration real;    // real (i.e wall clock) time
            process_clock::duration user;    // user cpu time
            process_clock::duration system;  // system cpu time
        };

[endsect]

[endsect]
[section:process_times Typedef `process_times`]

    typedef process_clock::process_times process_times;

This is a synonym of process_clock::process_times included for backward compatibility.

[endsect]

[section:process_timer Class `process_timer`]

Knowing how long a program takes to execute is useful in both test and production environments. It is also helpful if such timing information is broken down into real (wall clock) time, CPU time spent by the user, and CPU time spent by the operating system servicing user requests.

`process_timer<>` is the `timer<>` equivalent associated to the pseudo-clock `process_clock`. It behaves like `timer<>` but it uses the specific `process_clock:now()` function.

        class process_timer {
        public:
            typedef process_clock                          clock;
            typedef process_clock::duration                duration;
            typedef process_clock::time_point              time_point;

            explicit process_timer( system::error_code & ec = system::throws );

            ~process_timer();
            void  start( system::error_code & ec = system::throws );
            void  elapsed( process_times & times, system::error_code & ec = system::throws );
        };

[endsect]
[section:run_timer Class `run_timer`]

class `run_timer` provides a complete run-time reporting package that can be invoked in a single line of code. The reporting is controlled by two parameters:

* format : The output format
* places(precision): the number of decimal placess used.

The default places is given by default_places and is 3.

The default format is "nreal %rs, cpu %cs (%p%), user %us, system %ss\\n", where

* `%r` : real process clock
* `%u` : user process clock
* `%s` : system process clock
* `%c` : user+system process clock
* `%p` : percentage (user+system)/real process clock

All the units are given using the suffix "s" following the System International d'Unites Std.

        class run_timer : public process_timer {
        public:
            explicit run_timer( system::error_code & ec = system::throws );
            explicit run_timer( std::ostream & os,
                        system::error_code & ec = system::throws );

            explicit run_timer( const std::string & format,
                        system::error_code & ec = system::throws );
            explicit run_timer( std::ostream & os, const std::string & format,
                        system::error_code & ec = system::throws );

            explicit run_timer( const std::string & format, int places,
                        system::error_code & ec = system::throws );
            explicit run_timer( std::ostream & os, const std::string & format, int places,
                        system::error_code & ec = system::throws );

            explicit run_timer( int places,
                        system::error_code & ec = system::throws );
            explicit run_timer( std::ostream & os, int places,
                        system::error_code & ec = system::throws );

            explicit run_timer( int places, const std::string & format,
                        system::error_code & ec = system::throws );
            explicit run_timer( std::ostream & os, int places, const std::string & format,
                        system::error_code & ec = system::throws );

            ~run_timer();

            void start( system::error_code & ec = system::throws );

            void report( system::error_code & ec = system::throws );

            void test_report( duration real_, duration user_, duration system_ );
            bool reported() const;
            static int default_places();
        };


[endsect]

[endsect]

[endsect]
]

[endsect]


[/=================]
[section Appendices]
[/=================]

[/==================================]
[section:history Appendix A: History]
[/==================================]

[section [*Version 1.1.0, Mars 17, 2011] ]

[*New Features:]

* [@http://svn.boost.org/trac/boost/ticket/???? #????] Added time_point unary operators +,-,++,-- and binary operators +=,-= with Rep al RHS.
* [@http://svn.boost.org/trac/boost/ticket/5323 #5323] 	Add Associated type difference_type for chrono::time_point.

[*Fixes:]

* [@http://svn.boost.org/trac/boost/ticket/5322 #5322] Explicit default constructed chrono::durations are uninitialized
 

[endsect] [/section [*Version 1.1.0, Mars 17, 2011] ]

[section [*Version 1.0.0, January 6, 2011] ]

* Moved chrono to trunk taking in account the review remarks.
* Documentation revision.

[*Features:]

* Boost_Chrono is now a configurable header-only library version (that also allows the user to choose if the `windows.h` file is included or not).
* Added clock_string<> traits.
* Define chrono-io for all the clocks.
* Add input of process_times representation.

[*Implementation:]

* Use of detail/win files to avoid the use of windows.h file.
* Completed the error_code handling.
* Works now with BOOST_SYSTEM_NO_DEPRECATED.

[*Fixes:]

* Fix some warnings.
* Fix original errors on Mac
* Don't fix the link with boost_system to static.

[*Test:]

* Added test on process and thread clocks.
* Moved to lightweight_test.hpp.
* Able to test multiple configurations.

[*Doc:]

* Removed some not useful parts as the test and the tickets.

[endsect] [/section [*Version 1.0.0, January 6, 2011] ]

[/
[section [*Version 0.6.0, September 22, 2010] ]

[*Features:]

* Added experimental chrono_io.

[*Fixes:]

* Fix duration values min implementation.
* Fix some warnings

[*Test:]

* Adapted test from libc++/chrono

[endsect]

[section [*Version 0.5.0, September 10, 2010] ]

[*Features:]

* Stopwatches, Ratio and CommonType have been moved to separated libraries: Boost.Stopwatches, Boost.Ratio and Boost.TypeTraits.

[endsect]

[section [*Version 0.4.7, September 1, 2010] ]

[*New Features:]

* Added __lightweight_stopwatch__.

[endsect]

[section [*Version 0.4.6, August 28, 2010] ]

[*New Features:]

* Implementation of __common_type without using Boost.TypeOf.
* Added __stopwatch_accumulator_time_formatter__ class.

[*Old Features:]

* Type reporter removed from Stopwatches as well as the get_reporter metafunction.

[*Bug Fixes]

* __process_cpu_clock is now a valid model of Clock that can be used with __stopclocks_accumulator__.
* eliminate or suppress a lot of warnings appearing with with warnings=all -Wextra
* improve the error code handling

[endsect]

[section [*Version 0.4.5, July 6, 2010] ['Documentation update]]

[*Documentation]

* Overview rewriting
* Added missing __thread_clock reference.
* How to implement a __thread_clock tutorial removed.
* References section renamed to External Resources.
* Added links to source examples.
* Added links between Models and Concepts.
* Added macros descriptions.
* Cleanup.

[*Bug Fixes]

* Valgrind fixes: "Conditional jump or move depends on uninitialised value(s)"
* Take care of Boost.System break on version 1.44
* gcc.4.4 "warning: suggest parentheses around '&&' within '||' " removal.

[endsect]

[section [*Version 0.4.4, February 22, 2010] [' Warning fixes]]

[*Bug Fixes]

* `scoped_suspend` warning removal
* `error_code` management completed

[endsect]

[section [*Version 0.4.3, June 18, 2010] ['Missing file fixe]]

[*Bug Fixes]

* boost/thread/detail/cv_status.hpp file was not commited.

[endsect]

[section [*Version 0.4.2, June 18, 2010] ['Packaging fixe]]

* Boost.Conversion library, used by Boost.Thread porting to Boost.Chrono was not packaged.

[endsect]

[section [*Version 0.4.1, June 17, 2010] ['Added thread clock implementation on Windows]]

[*New Features:]

* Added __thread_clock implementation on Windows.
* Added *Boost.Thread* using *Boost.Chrono*.

[endsect]

[section [*Version 0.4, February 28, 2010] ['New thread clock and Suspendible clock ]]

[*New Features:]

* __SuspendibleClock__ concept + template class _suspendible_clock__.
* Added `scope_suspend` which do `suspend`/`resume` if the __Clock is a model of __SuspendibleClock__ concept, and nothing otherwise.
* __thread_clock support on platforms providing it natively.
* Added support for wide character for __stopwatch_reporter__, `stopclock`, and `stopclock_accumulator`.
* `digital_time` renamed `t24_hours`.

[*Perf]

Added performances measures.

[*Bug Fixes]

* Bug on timeval_demo.

    time_point t(duration(xtime(0)));  // this was taken as a function declaration
    gettimeofday((timeval*)&t, 0);
    return t;
by

    timeval tv;
    gettimeofday(&tv, 0);
    xtime xt( tv.tv_sec, tv.tv_usec);
    return time_point(duration(xt));

* Bug on run_timer_test (add a global variable to avoid optimization that removes completely the code to be  measured

[endsect]

[section [*Version 0.3.2, January 25, 2010] ['New frequency, lifetime and percentage stopwatch_accumulator features]]
[*Features:]

* Added overloading for `operator/(Integer/Duration)`
* Added frequency, lifetime and percentage to the default `stopwatch_accumulator_formatter`.

[*Bug Fixes]
* Specific formatters didn't work completly.
* Replace `duration(0)` by `duration::zero()` on template classes.
* `suspend` doesn't works: `partial_` not initialized neither taken in account by the elapsed function.

[endsect]

[section [*Version 0.3.1, January 20, 2010] ['New support for wide characters]]
[*Features:]

* Support for wide characters on formatters and stopclocks
* added `chrono.hpp` and `stopwatches.hpp` at the boost level


[endsect]

[section [*Version 0.3.0, January 17, 2010] ['New stopwatch/stopclock feature + Bug fixes]]
[*Features:]

* Added independent process cpu clocks for real, user, system process CPU time
* Added global process cpu clock for real, user, system process CPU time
* Added `digital_time` (looking for a better name)
* Added new __Stopwatch__ concept measuring elapsed time between different points in time associated to the operations `start`, `stop`, `suspend` and `resume`.
* Added __stopwatch__ is a model __Stopwatch__ measuring the elapsed time between the `start` and the `stop` operations.
* Added __stopwatch_accumulator__ is a model __Stopwatch__ allowing to accumulate several time samples and gives the average, ...
* Added scoped helper classes allowing to pairwise `start`/`stop` operations, `suspend`/`resume` and `resume`/`suspend` a __Stopwatch__.
* Added new stopwatch __Formatter__ concept
    * Added stopwatch formatter "%ds\\n"
    * Added stopwatch accumulator formatter "%c times, sum=%ss, min=%ms, max=%Ms, mean=%as\\n"
    * Added time formatter "real %rs, cpu %cs (%p%), user %us, system %ss\\n"
    * Added digital_time formatter "%d days(s) %h:%m:%s.%n\\n"
* __stopwatch_reporter__ is a convenient generic class reporting elapsed time for the Stopwatch concept.
* Added `stopclock<Clock>` shortcut `stopwatch_reporter<stopwatch<Clock>>`
* Added __scoped_stopclock__ which trace at the constuctor and destructor.
* Added `typeof` registration for classes __duration and __time_point

* The old classes `process_times`, `process_clock`, `process_timer`, `timer` and `run_timer` are deprecated as the preceding additions are more generic. However for backward compatibility they preserved until inclusion of the library in Boost. Next follows the equivalences:
    * `timer<>` ~ `stopwatch<>`
    * `process_timer` ~ `stopwatch<process_cpu_clock>`
    * `run_timer` ~ `stopclock<>`

[*Bug Fixes]

* Try to correct warning "C4251: 'boost::chrono::run_timer::m_format' : class 'std::basic_string<_Elem,_Traits,_Ax>' needs to have dll-interface to be used by clients of class 'boost::chrono::run_timer'", by don't including inlines functions using the std::string `m_format`.

[endsect]

[section [*Version 0.2.1, December 13, 2009] ['Bug fixes]]

[*Bug Fixes]

* Replace `INTMAX_C` by `BOOST_INTMAX_C` until `boost/cstdint.hpp` ensures `INTMAX_C` is always defined.
* Define __BOOST_CHRONO_HAS_CLOCK_STEADY__ when `BOOST_CHRONO_WINDOWS_API`
* Commenting invalid operator declarations
* Take care of Boost `min`/`max` recommendations
* Complete qualification when defining nested typedef duration on clocks to avoid the following compile error:

    ./boost/chrono/chrono.hpp:945: error: declaration of 'typedef class boost::chrono::duration<long long int, boost::__ratio<1ll, 10000000ll> > boost::chrono::system_clock::duration'
    ./boost/chrono/chrono.hpp:458: error: changes meaning of 'duration' from 'class boost::chrono::duration<long long int, boost::__ratio<1ll, 10000000ll> >'

* cleanup of simulated...
* warning removal on `posix/process_clock.cpp`.
* disable VC++ foolishness.
* Update Jamfiles to manage with dll.
* removal of conversion warning in test_duration.
* manage with MSVC reporting a warning instead of an error when there is an integral constant overflow.
* Use `STATIC_ASSERT` specific macro to solve the compile failing issue.
* Qualify with `boost::detail` `boost::chrono::detail` to avoid ambiguities with MSVC.


[*Documentation:]

More updated documentation.

[endsect]

[section [*Version 0.2.0, December 8, 2009] ['+ Features + Bug fixes + Updated documentation]]

[*Features:]

* Added __ratio construction and assignment from an equivalent __ratio ([@http://home.roadrunner.com/~hinnant/issue_review/lwg-active.html#1281 [*LWG 1281. CopyConstruction and Assignment between ratios having the same normalized form]])
* Added nested __ratio typedef type ([@http://home.roadrunner.com/~hinnant/issue_review/lwg-active.html#1281 [*LWG 1281. CopyConstruction and Assignment between ratios having the same normalized form]])
* Added __BOOST_CHRONO_HAS_CLOCK_STEADY__ macro to state if __steady_clock is provided on this platform.
* Added __duration `operator%` ([@http://home.roadrunner.com/~hinnant/issue_review/lwg-defects.html#934 [*LGW 934. duration is missing operator%]])
* Added constexpr when constexpr should be used.
* Complete __duration `operator*` and `operator/`.


[*Implementation:]

* Use `INTMAC_C` to name `intmax_t` constants instead of `LL`.
* Separate `chrono.cpp` on # files `win/chrono.cpp`, `mac/chrono.cpp` and `posix/chrono.cpp` to make easier the maintenance on different platforms.
* Separate `process_clock.cpp` on # files `win/process_clock.cpp`, `mac/process_clock.cpp` and `posix/process_clock.cpp` to make easier the maintenace on different platforms.
* Added the `error_code` prototype for `steady_clock::now` for `mac/chrono.cpp`.
* Fully implement `mac/chrono.cpp` with error handling.
* Take care on POSIX systems when `CLOCK_STEADY` is not defined.

[*Documentation:]

* The documentation is written now using quick-book using as base [@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm [*N2661 - A Foundation to Sleep On]] .

[*Bug Fixes]

* `operator/` was ambiguous: Disambiguate duration `operator/`.
* `CLOCK_STEADY` is not defined with cygwin/gcc 3.4: Disable code when __BOOST_CHRONO_HAS_CLOCK_STEADY__ is not defined.
* result of metafunctions `ratio_multiply` and `ratio_divide` were not normalized ratios: Use of the nested __ratio typedef type on __ratio arithmetic operations.
* Copy constructor from similar __duration masked the defaulted operations: Added duration defaulted implementations


[endsect]
[section [*Version 0.1.0, April 29, 2009] ['Beman's boostified version Chrono]]

[*Features:]

*  The C++0x Standard Library's __common_type.
*  The C++0x Standard Library's compile-time rational arithmetic.
*  The C++0x Standard Library's time utilities, including:
    * Class template __duration
    * Class template __time_point
    * Clocks:
        * __system_clock
        * __steady_clock
        * `high_resolution_clock`

* Class template timer, with typedefs:
    * `system_timer`
    * `steady_timer`
    * `high_resolution_timer`

* Process clocks and timers:
    * `process_clock`, capturing real, user-CPU, and system-CPU times.
    * `process_timer`, capturing elapsed real, user-CPU, and system-CPU times.
    * `run_timer`, convenient reporting of process_timer results.


[endsect]
]
[endsect]

[/======================================]
[section:rationale Appendix B: Rationale]

See [@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm [*N2661 - A Foundation to Sleep On]] which is very informative and provides motivation for key design decisions. This section contains some extracts from this document.

[heading Why duration needs operator%]

This operator is convenient for computing where in a time frame a given duration lies. A motivating example is converting a duration into a "broken-down" time duration such as hours::minutes::seconds:

    class ClockTime
    {
        typedef boost::chrono::hours hours;
        typedef boost::chrono::minutes minutes;
        typedef boost::chrono::seconds seconds;
    public:
        hours hours_;
        minutes minutes_;
        seconds seconds_;

        template <class Rep, class Period>
          explicit ClockTime(const boost::chrono::duration<Rep, Period>& d)
            : hours_  (boost::chrono::duration_cast<hours>  (d)),
              minutes_(boost::chrono::duration_cast<minutes>(d % hours(1))),
              seconds_(boost::chrono::duration_cast<seconds>(d % minutes(1)))
              {}
    };

[endsect]


[/======================================================]
[section:implementation Appendix C: Implementation Notes]

[heading Which APIs have been chosen to implement each clock on each platform?]

The following table presents a resume of which API is uused for each clock on each platform
[table Clock API correspondence
    [[Clock]                                [Windows Platform]          [Posix Platform]                 [Mac Platform]  ]
    [[__system_clock]                     [GetSystemTimeAsFileTime]   [clock_gettime( CLOCK_REALTIME)] [gettimeofday]          ]
    [[__steady_clock]                  [QueryPerformanceCounter and QueryPerformanceFrequency]
                                        [clock_gettime( CLOCK_STEADY)] [mach_timebase_info,mach_absolute_time]          ]
    [[__process_real_cpu_clock]           [GetProcessTimes]           [times]                         [times]  ]
    [[__process_system_cpu_clock]         [GetProcessTimes]           [times]                         [times]    ]
    [[__process_user_cpu_clock]           [GetProcessTimes]           [times]                         [times]  ]
    [[__process_cpu_clock]                [GetProcessTimes]           [times]                         [times]   ]
    [[__thread_clock]                     [GetThreadTimes]            [clock_gettime(pthread_getcpuclockid)]         [clock_gettime(pthread_getcpuclockid)]       ]
]

[endsect]

[/======================================================]
[section:faq Appendix D: FAQ]

[heading Why does process_cpu_clock sometimes give more cpu seconds than real seconds?]

Ask your operating system supplier. The results have been inspected with a debugger, and both for Windows and Linux, that's what the OS appears to be reporting at times.


[heading Are integer overflows in the duration arithmetic detected and reported?]

[*Boost.Ratio] avoids all kind of overflow that could result of arithmetic operation and that can be simplified. The typedefs durations don't detect overflow. You will need a duration representation that handles overflow.

[heading Which clocks should be used to benchmarking?]

Each clock has his own features. It depends on what do you need to benchmark. Most of the time, you could be interested in using a thread clock, but if you need to measure code subject to synchronization a process clock would be better. If you have a multi-process application, a system-wide clock could be needed.

[heading Which clocks should be used for watching?]

For trace purposes, it is probably best to use a system-wide clock.

[endsect] [/section:faq Appendix D: FAQ]

[/====================================================]
[section:acknowledgements Appendix E: Acknowledgements]

The library's code was derived from Howard Hinnant's time2_demo prototype. Many thanks to Howard for making his code available under the Boost license. The original code was modified by Beman Dawes to conform to Boost conventions.

time2_demo contained this comment:

Much thanks to Andrei Alexandrescu, Walter Brown, Peter Dimov, Jeff Garland, Terry Golubiewski, Daniel Krugler, Anthony Williams.

The file <boost/chrono_io.hpp> has been adapted from the experimental header `<chrono_io>` from Howard Hinnant. Thanks for all Howard.

Howard Hinnant, who is the real author of the library, has provided valuable feedback and suggestions during the development of the library. In particular, The chrono_io_io.hpp source has been adapted from the experimental header `<chrono_io>` from Howard Hinnant.

The acceptance review of Boost.Ratio took place between November 5th and 15th 2010. Many thanks to Anthony Williams, the review manager, and to all the reviewers: David Deakins, John Bytheway, Roland Bock and Paul A. Bristow.

Thanks to Ronald Bock, Andrew Chinoff, Paul A. Bristow and John Bytheway for his help polishing the documentation.

Thanks to Tom Tan for reporting some compiler issues with MSVC V10 beta and MinGW-gcc-4.4.0 and for the many pushing for an homogeneous `process_cpu_clock` clock.

Thanks to Ronald Bock for reporting Valgind issues and for the many suggestions he made concerning the documentation.

[endsect]

[/
[/====================================================]
[section:tests  Appendix F: Tests]

In order to test you need to do.

    bjam libs/chrono/test

You can also run a specific suite of test by doing

    cd libs/chrono/test
    bjam chrono


[section chrono]
[table
    [[Name]             [kind]          [Description]          [Result] [Ticket]]
    [[chrono_unit_test]      [run]           [...]                  [Pass]   [#]]
    [[explore_limits]      [run]           [...]                  [Pass]   [#]]
    [[test_duration]      [run]           [...]                  [Pass]   [#]]
    [[test_clock]      [run]           [...]                  [Pass]   [#]]
    [[miscellaneous]      [run]           [...]                  [Pass]   [#]]
    [[test_special_values]      [run]           [...]                  [Pass]   [#]]
    [[manipulate_clock_object]      [run]           [...]                  [Pass]   [#]]
    [[chrono_accuracy_test]      [run]           [...]                  [Pass]   [#]]

]
[endsect]

[section examples]
[table
    [[Name]             [kind]          [Description]          [Result] [Ticket]]
    [[cycle_count]      [run]           [...]                  [Pass]   [#]]
    [[runtime_resolution]      [run]           [...]                  [Pass]   [#]]
    [[xtime]      [run]           [...]                  [Pass]   [#]]
    [[saturating]      [run]           [...]                  [Pass]   [#]]
    [[min_time_point]      [run]           [...]                  [Pass]   [#]]
    [[i_dont_like_the_default_duration_behavior]      [run]           [...]                  [Pass]   [#]]
    [[simulated_thread_interface_demo]      [run]           [...]                  [Pass]   [#]]
    [[timeval_demo]      [run]           [...]                  [Pass]   [#]]
]
[endsect]


[section Other Clocks]
[table
    [[Name]                         [kind]          [Description]           [Result] [Ticket]]
    [[test_thread_clock]               [run]           [test basic uses of thread_clock.]                   [Pass]   [#]]
]
[endsect]

[section:typedefs Duration Typedef's]
[table
    [[Name]                 [kind]  [Description]                               [Result] [Ticket]]
    [[hours.pass]           [run]   [check how many hours we can count.]        [Pass]   [#]]
    [[minutes.pass]         [run]   [check how many minutes we can count.]      [Pass]   [#]]
    [[seconds.pass]         [run]   [check how many seconds we can count.]      [Pass]   [#]]
    [[milliseconds.pass]    [run]   [check how many milliseconds we can count.] [Pass]   [#]]
    [[microseconds.pass]    [run]   [check how many microseconds we can count.] [Pass]   [#]]
    [[nanoseconds.pass]     [run]   [check how many nanoseconds we can count.]  [Pass]   [#]]
]
[endsect]

[section traits]
[table
    [[Name]                                 [kind]  [Description]                                                                   [Result] [Ticket]]
    [[specialization.duration.pass]         [run]   [check the correct common_type specialization has been done for duration.]      [Pass]   [#]]
    [[specialization.time_point.pass]       [run]   [check the correct common_type specialization has been done for time_point.]    [Pass]   [#]]
    [[is_fp.treat_as_floating_point.pass]   [run]   [check treat_as_floating_point<T> inherits from is_floating_point<T>.]          [Pass]   [#]]
    [[duration_values.max.pass]             [run]   [check  max() corresponds to std::numeric_limits<T>::max().]                    [Pass]   [#]]
    [[duration_values.min.pass]             [run]   [check min() corresponds to std::numeric_limits<T>::lowest().]                  [Pass]   [#]]
    [[duration_values.zero.pass]            [run]   [check zero is 0.]                                                              [Pass]   [#]]
]
[endsect]

[section duration]
[table
    [[Name]                 [kind]          [Description]                                                       [Result] [Ticket]]
    [[duration.fail]        [compile-fail]  [If a program instantiates duration with a duration type for the template argument Rep a diagnostic is required.]                                                                                                      [Pass]   [#]]
    [[ratio.fail]           [compile-fail]  [Period shall be a specialization of ratio, diagnostic required..]  [Pass]   [#]]
    [[positive.fail]        [compile-fail]  [Period::num shall be positive, diagnostic required..]              [Pass]   [#]]
    [[defaul_ratio.pass]    [run]           [Test default template arg.]                                        [Pass]   [#]]
    [[types.pass]           [run]           [Test nested types.]                                                [Pass]   [#]]

    [[arithmetic.op_divide_ass.pass]        [run]   [check duration& operator/=(const rep& rhs);]       [Pass]   [#]]
    [[arithmetic.op_minusminusint.pass]     [run]   [check duration operator--(int);]                   [Pass]   [#]]
    [[arithmetic.op_plus_ass.pass]          [run]   [check duration& operator+=(const duration& d);]    [Pass]   [#]]
    [[arithmetic.op_minus.pass]             [run]   [check duration operator-() const;]                 [Pass]   [#]]
    [[arithmetic.op_mod_ass_duration.pass]  [run]   [check duration& operator%=(const duration& rhs);]  [Pass]   [#]]
    [[arithmetic.op_plusplus.pass]          [run]   [check duration& operator++();.]                    [Pass]   [#]]
    [[arithmetic.op_minus_ass.pass]         [run]   [check duration& operator-=(const duration& d);]    [Pass]   [#]]
    [[arithmetic.op_mod_ass_rep.pass]       [run]   [check duration& operator%=(const rep& rhs)]        [Pass]   [#]]
    [[arithmetic.op_plusplusint.pass]       [run]   [check duration operator++(int);]                   [Pass]   [#]]
    [[arithmetic.op_minusminus.pass]        [run]   [check duration operator--();]                      [Pass]   [#]]
    [[arithmetic.op_plus.pass]              [run]   [check duration operator+() const;]                 [Pass]   [#]]
    [[arithmetic.op_times_ass.pass]         [run]   [check duration& operator*=(const rep& rhs);.]      [Pass]   [#]]

    [[cast.duration_cast.pass]  [run]           [check template <class ToDuration, class Rep, class Period> ToDuration duration_cast(const duration<Rep, Period>& d);]                                                                                                           [Pass]  [#]]
    [[cast.toduration.fail]     [compile-fail]  [check ToDuration shall be an instantiation of duration.]   [Pass]   [#]]

    [[comparisons.op_equal.pass]            [run]           [check operator==() and operator!=().]  [Pass]   [#]]
    [[comparisons.op_less.pass]             [run]           [check operators <,<=,>,>=.]            [Pass]   [#]]

]
[table
    [[Name]                         [kind]          [Description]           [Result] [Ticket]]

    [[cons.convert_exact.pass]              [run]           [check exact conversions allowed for integral reps.]                    [Pass]   [#]]
    [[cons.convert_float_to_int.fail]       [compile-fail]  [check conversions from floating-point to integral durations disallowed.]   [Pass]   [#]]
    [[cons.convert_inexact.fail]            [compile-fail]  [check inexact conversions disallowed for integral reps.]               [Pass]   [#]]
    [[cons.convert_inexact.pass]            [run]           [check inexact conversions allowed for floating-point reps.]            [Pass]   [#]]
    [[cons.convert_int_to_float.pass]       [run]           [check conversions from integral to floating-point durations allowed.]  [Pass]   [#]]
    [[cons.default.pass]                    [run]           [check Rep must be default initialized, not initialized with 0.]        [Pass]   [#]]
    [[cons.rep.pass]                        [run]           [check explicit duration(const Rep2& r).]                               [Pass]   [#]]
    [[cons.rep01.fail]                      [compile-fail]  [test for explicit.]                                                    [Pass]   [#]]
    [[cons.rep02.fail]                      [compile-fail]  [check Rep2 shall be implicitly convertible to rep.]                    [Pass]   [#]]
    [[cons.rep02.pass]                      [run]           [check construct double with int.]                                      [Pass]   [#]]
    [[cons.rep03.fail]                      [compile-fail]  [treat_as_floating_point<Rep2>::value shall be false.]                  [Pass]   [#]]

    [[nonmember.op_plus.pass]               [run]           [check operator+(d,d).]                   [Pass]   [#]]
    [[nonmember.op_minus.pass]              [run]           [check operator-(d,d).]                   [Pass]   [#]]
    [[nonmember.op_divide_duration.pass]    [run]           [check operator/(d,d).]                   [Pass]   [#]]
    [[nonmember.op_divide_rep.fail]         [compile-fail]  [check operator/(d,r) fails with different rep.]                   [Pass]   [#]]
    [[nonmember.op_divide_rep.pass]         [run]           [check operator/(d,r).]                   [Pass]   [#]]
    [[nonmember.op_mod_duration.pass]       [run]           [check operator%(d,d).]                   [Pass]   [#]]
    [[nonmember.op_mod_rep.pass]            [run]           [check operator%(d,r).]                   [Pass]   [#]]
    [[nonmember.op_times_rep.pass]          [run]           [check operator*(d,r).]                   [Pass]   [#]]
    [[nonmember.op_times_rep1.fail]         [compile-fail]  [check operator*(d,r) fails with different rep.]                   [Pass]   [#]]
    [[nonmember.op_times_rep2.fail]         [compile-fail]  [check operator*(r,d) fails with different rep.]                   [Pass]   [#]]
    [[special.max.pass]               [run]           [check coherency between max and duration_values traits.]                   [Pass]   [#]]
    [[special.min.pass]               [run]           [check coherency between min and duration_values traits.]                   [Pass]   [#]]
    [[special.zero.pass]               [run]           [check coherency between zero and duration_values traits.]                   [Pass]   [#]]
]
[endsect]

[section time_point]
[table
    [[Name]                         [kind]          [Description]           [Result] [Ticket]]
    [[default_duration.pass]               [run]           [check .]                   [Pass]   [#]]
    [[duration.fail]               [compile-fail]           [check .]                   [Pass]   [#]]

    [[arithmetic.op_plus_ass.pass]               [run]           [check .]                   [Pass]   [#]]
    [[arithmetic.op_plus_ass.pass]               [run]           [check .]                   [Pass]   [#]]
    [[cast.time_point_cast.pass]               [run]           [check .]                   [Pass]   [#]]
    [[cast.toduration.fail]               [compile-fail]           [check .]                   [Pass]   [#]]
    [[comparisons.op_equal.fail]               [compile-fail]           [check .]                   [Pass]   [#]]
    [[comparisons.op_equal.pass]               [run]           [check .]                   [Pass]   [#]]
    [[comparisons.op_less.fail]               [compile-fail]           [check .]                   [Pass]   [#]]
    [[comparisons.op_less.pass]               [run]           [check .]                   [Pass]   [#]]
    [[cons.convert.fail]               [compile-fail]           [check .]                   [Pass]   [#]]
    [[cons.convert.pass]               [run]           [check .]                   [Pass]   [#]]
    [[cons.default.pass]               [run]           [check .]                   [Pass]   [#]]
    [[cons.duration..fail]               [compile-fail]           [check .]                   [Pass]   [#]]
    [[cons.duration.pass]               [run]           [check .]                   [Pass]   [#]]
    [[nonmember.op_plus.pass]               [run]           [check .]                   [Pass]   [#]]
    [[nonmember.op_minus_time_point.pass]               [run]           [check .]                   [Pass]   [#]]
    [[nonmember.op_minus_duration.pass]               [run]           [check .]                   [Pass]   [#]]
    [[special.max.pass]               [run]           [check .]                   [Pass]   [#]]
    [[special.min.pass]               [run]           [check .]                   [Pass]   [#]]
]
[endsect]

[section clock]
[table
    [[Name]                         [kind]          [Description]           [Result] [Ticket]]
    [[hires.consistency.pass]               [run]           [check .]                   [Pass]   [#]]
    [[hires.now.pass]               [run]           [check .]                   [Pass]   [#]]
    [[steady.consistency.pass]               [run]           [check .]                   [Pass]   [#]]
    [[steady.now.pass]               [run]           [check .]                   [Pass]   [#]]
    [[system.consistency.pass]               [run]           [check .]                   [Pass]   [#]]
    [[system.now.pass]               [run]           [check .]                   [Pass]   [#]]
    [[system.from_time_t.pass]               [run]           [check .]                   [Pass]   [#]]
    [[system.rep_signed.pass]               [run]           [check .]                   [Pass]   [#]]
    [[system.rep_signed.pass]               [run]           [check .]                   [Pass]   [#]]
    [[process.consistency.pass]               [run]           [check .]                   [Pass]   [#]]
    [[process.now.pass]               [run]           [check .]                   [Pass]   [#]]
    [[thread.consistency.pass]               [run]           [check .]                   [Pass]   [#]]
    [[thread.now.pass]               [run]           [check .]                   [Pass]   [#]]
]


[endsect]


[section io examples]
[table
    [[Name]                         [kind]          [Description]           [Result] [Ticket]]
    [[io_ex1.pass]               [run]           [check .]                   [Pass]   [#]]
    [[io_ex2.pass]               [run]           [check .]                   [Pass]   [#]]
    [[io_ex3.pass]               [run]           [check .]                   [Pass]   [#]]
    [[io_ex4.pass]               [run]           [check .]                   [Pass]   [#]]
    [[io_ex5.pass]               [run]           [check .]                   [Pass]   [#]]
]
[endsect]



[endsect]
[/=====================================]
[section:tickets  Appendix G: Tickets]

[table
    [[Ticket]             [Description]          [Resolution] [State]]
    [[0]    [ Issues raised by Michael Marcin:  In the past I've seen QueryPerformanceCounter give incorrect results,
    especially with SpeedStep processors on laptops. This was many years ago and
    might have been fixed by service packs and drivers.

    Typically you check the results of QPC against GetTickCount to see if the
    results are reasonable.
    http://support.microsoft.com/kb/274323

    I've also heard of problems with QueryPerformanceCounter in multi-processor
    systems.

    I know some people SetThreadAffinityMask to 1 for the current thread call
    their QueryPerformance* functions then restore SetThreadAffinityMask. This
    seems horrible to me because it forces your program to jump to another
    physical processor if it isn't already on cpu0 but they claim it worked well
    in practice because they called the timing functions infrequently.

    In the past I have chosen to use timeGetTime with timeBeginPeriod(1) for
    high resolution timers to avoid these issues.
    ] [???] [*Open*]]
    [[1]    [operator/ was ambiguous] [Disambiguate duration operator/]                  [Closed]]
    [[2]    [CLOCK_STEADY is not defined with cygwin/gcc 3.4] [Disable code when BOOST_CHRONO_HAS_CLOCK_STEADY is not defined.]                  [Closed]]
    [[3]    [result of metafunctions ratio_multiply and ratio_divide were not normalized ratios] [Use of the nested ratio typedef type on ratio arithmetic operations.]                  [Closed]]
    [[4]    [Copy constructor from similar duration masked the defaulted operations] [Added duration defaulted implementations]                  [Closed]]
    [[5]    [INTMAX_C is not always defined] [Replace INTMAX_C by BOOST_INTMAX_C until boost/cstdint.hpp ensures INTMAX_C is always defined.]                  [Closed]]
    [[6]    [undefined BOOST_CHRONO_HAS_CLOCK_STEADY when BOOST_CHRONO_WINDOWS_API] [Define BOOST_CHRONO_HAS_CLOCK_STEADY when BOOST_CHRONO_WINDOWS_API]                  [Closed]]
    [[7]    [min/max macros intrussion] [Take care of Boost min/max recommendations]                  [Closed]]
    [[8]    [declaration of 'typedef class boost::chrono::duration<..> changes meaning of 'duration'] [complete qualification when defining nested typedef duration on clocks to avoid the following compile error:]                  [Closed]]
    [[9]    [VC++ warnings] [disable VC++ foolishness]                  [Closed]]
]
[table
    [[Ticket]             [Description]          [Resolution] [State]]

    [[10]    [conversion warning in test_duration] [removal of conversion warning in test_duration]                  [Closed]]
    [[11]    [MSVC reports a warning instead of an error when there is an integral constant overflow] [manage with MSVC reporting a warning instead of an error when there is an integral constant overflow]                  [Closed]]
    [[12]    [ambiguities with MSVC when using detail:: namespace] [Qualify with boost::detail boost::chrono::detail ]                  [Closed]]
    [[13]    [warning C4251: 'boost::chrono::run_timer::m_format' : class 'std::basic_string<_Elem,_Traits,_Ax>' needs to have dll-interface to be used by clients of class 'boost::chrono::run_timer'] [don't include inlines functions using the std::string m_format]                  [Closed]]
    [[14]    [Bad use of duration(0) on template classes] [remplace by duration::zero()]                  [Closed]]
    [[15]    [suspend doesn't works: partial_ not initialized] [initialize with duration::zero()]                  [Closed]]
    [[16]    [suspend doesn't works: elapsed doesn't take care of partial_] [take care of partial]                  [Closed]]
    [[17]    [suspend doesn't works: bad use of system::error_code & ec] [replace by system::error_code ec]                  [Closed]]
    [[18]    [warnings on mingw-gcc.4.4:

..\..\../boost/chrono/chrono.hpp: In copy constructor 'boost::chrono::time_point<boost::chrono::process_cpu_clock,
boost::chrono::duration<boost::chrono::process_cpu_clock::times, boost::ratio<1ll, 1000000000ll> >
>::time_point(const boost::chrono::time_point<boost::chrono::process_cpu_clock,
boost::chrono::duration<boost::chrono::process_cpu_clock::times, boost::ratio<1ll, 1000000000ll> > >&)':
..\..\../boost/chrono/chrono.hpp:816: warning: suggest parentheses around '&&' within '||'
..\..\../boost/chrono/chrono.hpp:816: warning: suggest parentheses around '&&' within '||'

] [???]                  [Closed]]
    [[19]    [Use of Specific formatters doesn't works] []                  [Closed]]

    [[20]    [boost/chrono/scoped_suspend.hpp(31) : warning C4520: 'boost::chrono::scoped_suspend<Clock>' : multiple default constructors specified
] [Remove the default constructor deletion ]                  [Closed]]
    [[21]    [suspendible_clock_test doesn't works in my mingw environement] [(issue with tss)]                  [*Open*]]
    [[22]    [error_code not initialized] [Use ec.clear() before throwing a exception.]                  [Closed]]
    [[23]    [boost/thread/detail/cv_status.hpp file was not commited] [commit file]                  [Closed]]
    [[24]    [Boost.Conversion was not packaged] [Package it]                  [Closed]]
    [[25]    [Valgrind issue: Conditional jump or move depends on uninitialised value(s)] [Replace the test]                  [Closed]]
    [/[#]    [XXXX] [XXXX]                  [Closed]]
]





[endsect]

]
[/=====================================]
[section:todo  Appendix F: Future plans]
[/=====================================]

[heading For later releases]

* Add chrono utilities as defined By Howard Hinnant [@http://home.roadrunner.com/~hinnant/duration_io/chrono_util.html here].

[endsect]

[endsect]
