Search code examples
c++c++-chrono

Determine the part of chrono durations


I would like to compute which part of one duration contains in another duration. There is standard implementation for integers (6), but it gives me 0 (due to integer divison) for the following example:

auto s = 1s;
auto ms = 200ms;
std::cout << ms / s; // 0, but I want 0.2 here

Is there a more elegant and generic way to compute a such value instead of the following ugly solution?

#include <chrono>
#include <iostream>

int main()
{
    using namespace std::chrono_literals;    

    auto s = 1s;
    auto ms = 200ms;

    const auto part = 1. * ms.count() / std::chrono::duration_cast<decltype(ms)>(s).count();

    std::cout << part << '\n';
}

One smart way is to use 1. / (s / ms);, but it's not fit for any duration types.


Solution

  • Use a double based duration.

    #include <chrono>
    #include <iostream>
    
    int main()
    {
        using namespace std::chrono_literals;    
        using my_seconds = std::chrono::duration<double>;
    
        my_seconds s = 1s;
        my_seconds ms = 200ms;
    
        std::cout << ms / s << '\n';
    }