Search code examples
boostboost-date-time

How do I instantiate a boost::date_time::time_duration with nanoseconds?


I feel like I'm missing something obvious here. I can easily make a time_duration with milliseconds, microseconds, or seconds by doing:

time_duration t1 = seconds(1);
time_duration t2 = milliseconds(1000);
time_duration t3 = microseconds(1000000);

But there's no function for nanoseconds. What's the trick to converting a plain integer nanoseconds value to a time_duration?

I'm on amd64 architecture on Debian Linux. Boost version 1.55.


Solution

  • boost::posix_time::microseconds is actually subsecond_duration<boost::posix_time::time_duration, 1000000>. So...

    #include <boost/date_time/posix_time/posix_time.hpp>
    
    using nanoseconds = boost::date_time::subsecond_duration<boost::posix_time::time_duration, 1000000000>;
    int main() {
        boost::posix_time::time_duration t = nanoseconds(1000000000);
    
        std::cout << t << "\n";
    }
    

    Prints

    00:00:01
    

    UPDATE

    Indeed, in the Compile Options for the Boost DateTime library you can see that there's an option to select nanosecond resolution:

    By default the posix_time system uses a single 64 bit integer internally to provide a microsecond level resolution. As an alternative, a combination of a 64 bit integer and a 32 bit integer (96 bit resolution) can be used to provide nano-second level resolutions. The default implementation may provide better performance and more compact memory usage for many applications that do not require nano-second resolutions.

    To use the alternate resolution (96 bit nanosecond) the variable BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG must be defined in the library users project files (ie Makefile, Jamfile, etc). This macro is not used by the Gregorian system and therefore has no effect when building the library.

    Indeed, you can check it using:

    Live On Coliru

    #define BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG
    #include <boost/date_time/posix_time/posix_time.hpp>
    
    int main() {
        using namespace boost::posix_time;
        std::cout << nanoseconds(1000000000) << "\n";
    }