How to get elapsed time in seconds from boost :: timer :: cpu_timer?

The following sample code based on the documentation gives me the elapsed time in seconds from the timer object provided in boost.

boost::timer::cpu_timer timer; // ...do some work... const boost::timer::nanosecond_type oneSecond(1000000000LL); return timer.elapsed().user / oneSecond; 

The problem with this method is that I have this inconvenient magic number in my code. Is there any method in boost that can give me elapsed seconds from the nanosecond_type value available by calling expired (). User without having this magic number sitting on my code?

(EDIT :) Output:

Based on the accepted answer, I got this snippet in my production code:

 boost::timer::cpu_timer timer; // ...do some work... auto nanoseconds = boost::chrono::nanoseconds(timer.elapsed().user + timer.elapsed().system); auto seconds = boost::chrono::duration_cast<boost::chrono::seconds>(nanoseconds); std::cout << seconds.count() << std::endl; 
+4
source share
2 answers

As @jogojapan suggested, boost :: chrono would be a good choice. But you do not need long_cast <> if you use double as the base type.

 typedef boost::chrono::duration<double> sec; // seconds, stored with a double sec seconds = boost::chrono::nanoseconds(timer.elapsed().user); std::cout << seconds.count() << "s\n"; // gives the number of seconds, as double. 
+8
source

You must measure the number of ticks for every nanosecond on each hardware. Take a look at ( Timer function providing time in seconds nano using C ++ )

0
source

Source: https://habr.com/ru/post/1488196/


All Articles