2

Referring to Obtaining Time in milliseconds

Why does below code produce zero as output?

int main()
{
    steady_clock::time_point t1 = steady_clock::now();
    //std::this_thread::sleep_for(std::chrono::milliseconds(1500));
    steady_clock::time_point t2 = steady_clock::now();
    auto timeC = t1.time_since_epoch().count();
    auto timeD = t2.time_since_epoch().count();
    auto timeA = duration_cast<std::chrono::nanoseconds > ( t1.time_since_epoch()).count();
    auto timeB = duration_cast<std::chrono::nanoseconds > ( t2.time_since_epoch()).count();

    std::cout << timeC << std::endl;
    std::cout << timeB << std::endl;
    std::cout << timeD << std::endl;
    std::cout << timeA << std::endl;

    std::cout << timeB - timeA << std::endl;


    system("Pause");
    return 0;
}

The output:

14374083030139686
1437408303013968600
14374083030139686
1437408303013968600
0
Press any key to continue . . .

I suppose there should be a difference of few nanoseconds, because of instruction execution time.

Community
  • 1
  • 1
Gaurav K
  • 2,864
  • 9
  • 39
  • 68

2 Answers2

3

Under VS2012, steady_clock (and high_resolution_clock) uses GetSystemTimeAsFileTime, which has a very low resolution (and is non-steady to boot). This is acknowledged as a bug by Microsoft.

Your workaround is to use VS2015, use Boost.Chrono, or implement your own clock using QueryPerformanceCounter (see: https://stackoverflow.com/a/16299576/567292).

Community
  • 1
  • 1
ecatmur
  • 152,476
  • 27
  • 293
  • 366
2

Just because you ask it to represent the value in nanoseconds, doesn't mean that the precision of the measurement is in nanoseconds.

When you look at your output you can see that the count are nanoseconds / 100. That that means that the count is representing time in units of 100 nanoseconds. But even that does not tell you the period of the underlying counter on which steady_clock is built. All you know is it can't be better than 100 nanoseconds.

You can tell the actual period used for the counter by using the periodmember of the steady_clock

double periodInSeconds = double(steady_clock::period::num) 
                       / double(steady_clock::period::den);

Back to your question: "Why does below code produce zero as output?"

Since you haven't done any significant work between the two calls to now() it is highly unlikely that you have used up 100 nanoseconds, so the answers are the same -- hence the zero.

Dale Wilson
  • 9,166
  • 3
  • 34
  • 52