std::chrono::duration_cast - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::chrono::duration_cast

From cppreference.com
< cpp‎ | chrono‎ | duration

template <class ToDuration, class Rep, class Period> constexpr ToDuration duration_cast(const duration<Rep,Period>& d); |  | (since C++11)

Converts a std::chrono::duration to a duration of different type `ToDuration`.

No implicit conversions are used. Multiplications and divisions are avoided where possible, if it is known at compile time that one or more parameters are 1. Computations are done in the widest type available and converted, as if by `static_cast`, to the result type only when finished.

### [edit] Parameters

d | - | duration to convert

### [edit] Return value

`d` converted to a duration of type `ToDuration`.

### [edit] Notes

The function does not participate in the overload resolution unless `ToDuration` is an instance of std::chrono::duration.

Casting between floating-point durations or between integer durations where the source period is exactly divisible by the target period (e.g. hours to minutes) can be performed implicitly, no duration_cast is needed.

Casting from a floating-point duration to an integer duration is subject to undefined behavior when the floating-point value is NaN, infinity, or too large to be representable by the target's integer type.

### [edit] Example

This example measures the execution time of a function

Run this code

    #include <iostream>
    #include <chrono>
    #include <thread>

    void f()
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    int main()
    {
        auto t1 = std::chrono::high_resolution_clock::now();
        f();
        auto t2 = std::chrono::high_resolution_clock::now();
        std::cout << "f() took "
                  << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count()
                  << " milliseconds\n";
    }

Output:

    f() took 1000 milliseconds

### [edit] See also

time_point_cast | converts a time point to another time point on the same clock, with a different duration (function template) [edit]
floor(std::chrono::duration) (C++17) | converts a duration to another, rounding down (function template) [edit]
ceil(std::chrono::duration) (C++17) | converts a duration to another, rounding up (function template) [edit]
round(std::chrono::duration) (C++17) | converts a duration to another, rounding to nearest, ties to even (function template) [edit]

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