logoalt Hacker News

cyberaxtoday at 12:54 AM1 replyview on HN

C++ chrono is weird. It's both over-abstracted and yet has some thoughtless features that just negate this over-abstraction.

I remember not being able to represent the time in fractional units, like tertias (1/60-th of a second) but that was mostly an academic problem. More importantly, it was not possible to express duration as a compound object. I wanted to be able to represent the dates with nanosecond precision, but with more than 250 years of range. I think it is still not possible?


Replies

mpynetoday at 2:31 AM

Fractional time shouldn't be an issue as long as the ratio is a rational number. It's how durations are already handled behind the scenes.

Likewise it's annoying to cook up your own type, but as long as you can come up with 'number of ticks' type that acts like an arithmetic type then it should work with std::chrono. E.g. if I just Boost's Multiprecision library as a quick example:

    #include <chrono>
    #include <iostream>
    #include <boost/multiprecision/cpp_int.hpp>

    using namespace std::chrono_literals;

    int main()
    {
        using BigInt = boost::multiprecision::uint128_t;
        using BigNanos = std::chrono::duration<BigInt, std::nano>;

        std::cout << "Count for 1s: " << BigNanos(1s).count() << "\n";
        std::cout << "Count for 300 years: " << BigNanos(std::chrono::years(300)).count() << "\n";
    }
Then that code (when compiled with -std=c++20 or better) should output:

Count for 10s: 1000000000 Count for 300 years: 9467085600000000000

If you're willing to use gcc/clang builtins for 128-bit types you won't even need Boost or your own custom type to do basic arithmetic (but serializing the result may be difficult, not sure how gcc/clang handle that for custom 128-bit types).

show 1 reply