5

The following rough 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 uncomfortable magic number in my code. Is there some method within boost that can give me elapsed seconds out of the nanosecond_type value available from the call to elapsed().user, without having this magic number sitting in my code?

(EDIT:) Conclusion:

Based on the accepted answer, I ended up with 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;
Boinst
  • 3,365
  • 2
  • 38
  • 60
  • 2
    My first guess would be that `duration_cast` from `boost::chrono` can do this -- assuming that `chrono` and `timer` are compatible in this respect. – jogojapan Jun 26 '13 at 02:48
  • 2
    I'm not sure I'd feel uncomfortable about the magic number, as duration_cast simply pushes the magic down into boost. – Tanaya Oct 05 '15 at 21:26

3 Answers3

9

As @jogojapan suggested, boost::chrono would be a good choice. But you don't need the duration_cast<> if you use double as underlying 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.
mr_georg
  • 3,635
  • 5
  • 35
  • 52
  • based on your advice I wrote [some code](http://pastebin.com/gLva8zqU). I kept the duration_cast that @jogojapan suggested because it felt more readable. Testing now. – Boinst Jun 26 '13 at 23:35
  • I think the problem with this is that it cuts of the decimal part...? – Arne Jun 25 '18 at 10:52
1

One more addition:

double
getSeconds( const boost::timer::nanosecond_type& elapsed )
{
  return
    static_cast< double >(
      boost::chrono::nanoseconds( elapsed ).count()
    ) * boost::chrono::nanoseconds::period::num / boost::chrono::nanoseconds::period::den;
}

This you can call with timer.elapsed().user for example to get a double value of the elapsed time. This can obviously also transformed to std::chrono, if wanted / supported.

Arne
  • 2,624
  • 3
  • 24
  • 45
0

You should measure the number of tick per nanosecond on each Hardware your soft run.. take a look at ( Timer function to provide time in nano seconds using C++)

Community
  • 1
  • 1
alexbuisson
  • 7,699
  • 3
  • 31
  • 44
  • 1
    Thanks, but in this case, I'm specifically trying to use the class *boost::timer::cpu_timer*. – Boinst Jun 26 '13 at 06:04