logoalt Hacker News

mpynetoday at 2:31 AM1 replyview on HN

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).


Replies

cyberaxtoday at 2:41 AM

Yes, that was my problem. I could use the emulated uint128_t, but not a seconds+nano seconds pair. I need to re-check why...