how to measure time? [duplicate]

2019-09-18 06:00发布

问题:

This question already has an answer here:

  • resolution of std::chrono::high_resolution_clock doesn't correspond to measurements 3 answers

I know there are many topics for finding elapse time of a code and I have read many, but i really get confused I decided to use high resolution clock and ran this code to see how many times a second the clock ticks

cout << chrono::high_resolution_clock::period::den << endl;
output:10000000

and then I defined the begin time and the end time as below

int main()
{
    auto begin = std::chrono::high_resolution_clock::now();
    .
    .
    .
    .
    auto end = std::chrono::high_resolution_clock::now();
    cout<<"RUN TIME IS :"<<endl;
    std::cout << std::chrono:: duration_cast <chrono:: nanoseconds>(end-begin).count() << "ns" << std::endl;
    system("PAUSE");
    //**********************************************************
    return 0;
}

but most of the time the output is 0, but the code is more than 2000lines I waste a lot of time,but the problem has not solved yet . So please let me know is it a good way to determine the elapse time ? And what is the wrong with my code ? I am using VS2012 another question is that i want to measure a computation time of a problem and I am not sure which one should i measure(system time , user time or real time) ? Thank you in advance

回答1:

This is correct... But the clock is not actually required to be "high-resolution", that's implementation defined.

You may consider using an alternate method, which is built into the Windows API:

Check out the QueryPerformanceCounter APIs, as explained in this question.