find c++ execution time

后端 未结 6 1857
难免孤独
难免孤独 2021-01-13 09:34

I am curious if there is a build-in function in C++ for measuring the execution time? I am using Windows at the moment. In Linux it\'s pretty easy...

6条回答
  •  爱一瞬间的悲伤
    2021-01-13 10:10

    The best way on Windows, as far as I know, is to use QueryPerformanceCounter and QueryPerformanceFrequency.

    QueryPerformanceCounter(LARGE_INTEGER*) places the performance counter's value into the LARGE_INTEGER passed.

    QueryPerformanceFrequency(LARGE_INTEGER*) places the frequency the performance counter is incremented into the LARGE_INTEGER passed.

    You can then find the execution time by recording the counter as execution starts, and then recording the counter when execution finishes. Subtract the start from the end to get the counter's change, then divide by the frequency to get the time in seconds.

    LARGE_INTEGER start, finish, freq;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&start);
    // Do something
    QueryPerformanceCounter(&finish);
    std::cout << "Execution took " 
        << ((finish.QuadPart - start.QuadPart) / (double)freq.QuadPart) << std::endl;
    

提交回复
热议问题