1

Consider this example of code:

#include <chrono>
#include <iostream>

int main ( )
{
   using namespace std::chrono;

   system_clock::time_point s = system_clock::now();

   for (int i = 0; i < 1000000; ++i)
      std::cout << duration_cast<duration<double>>(system_clock::now() - s).count() << "\n";
}

I expect this to print the elapsed time in seconds. But it actually prints time in thousands of second (the expected result multiplied by 0.001). Am I doing something wrong?

Edit

Since seconds is equivalent to duration<some-int-type>, duration_cast<seconds> gives the same result.

I used gcc-4.7.3-r1

lisyarus
  • 15,025
  • 3
  • 43
  • 68
  • If you want seconds, you need to duration_cast – Dave F Feb 26 '14 at 11:19
  • @DaveF: Only if you want to round to a whole number of seconds, since `seconds` is a convenience typedef for `duration`. `duration` should also have a period of one second. – Mike Seymour Feb 26 '14 at 11:21
  • I tried it in VS2013 - works fine – GabiMe Feb 26 '14 at 11:39
  • How are you determining that it's printing milliseconds? If I compile and run that code, and watch the output, it increases by 1 each second as expected (that's with a slightly different version of GCC though). – Mike Seymour Feb 26 '14 at 11:39
  • 6
    [This](http://stackoverflow.com/questions/17405997/c-chrono-duration-cast-to-milliseconds-results-in-seconds) may help. – maverik Feb 26 '14 at 11:43
  • @maverik: that seems to be the right explanation. Thanks a lot. – lisyarus Feb 26 '14 at 14:54

3 Answers3

2

You program works as expected using both gcc 4.8.2 and VS2013. I think it might be a compiler bug in your old gcc 4.7

GabiMe
  • 18,105
  • 28
  • 76
  • 113
0

maverik guessed this right: the problem was with binary incompatibility inside std::chrono - gcc-4.8 version of libstdc++ and gcc-4.7 did not agree on internal units of time.

Community
  • 1
  • 1
lisyarus
  • 15,025
  • 3
  • 43
  • 68
-2

You could use duration_cast < seconds > instead of duration_cast < duration < double > >

const_ref
  • 4,016
  • 3
  • 23
  • 38
  • `seconds` is just a typedef for `duration`. `duration` should also have a period of one second. – Mike Seymour Feb 26 '14 at 11:22
  • I've already tried. seconds seem to act exactly like duration>, and duration_cast(...) in fact gives me seconds. – lisyarus Feb 26 '14 at 11:23
  • I get different results when using Ideone with C++11 compiler between the two(seconds and duration). Seconds only prints seconds(at least on that compiler). I cant test it on any other compiler atm however – const_ref Feb 26 '14 at 11:26