find c++ execution time

后端 未结 6 1825
难免孤独
难免孤独 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 09:59

    The functions you should use depend on the resolution of timer you need. Some of them give 10ms resolutions. Those functions are easier to use. Others require more work, but give much higher resolution (and might cause you some headaches in some environments. Your dev machine might work fine, though).

    http://www.geisswerks.com/ryan/FAQS/timing.html

    This articles mentions:

    • timeGetTime
    • RDTSC (a processor feature, not an OS feature)
    • QueryPerformanceCounter
    0 讨论(0)
  • 2021-01-13 10:06

    C++ has no built-in functions for high-granularity measuring code execution time, you have to resort to platform-specific code. For Windows try QueryPerformanceCounter: http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx

    0 讨论(0)
  • 2021-01-13 10:07

    It's pretty easy under Windows too - in fact it's the same function on both std::clock, defined in <ctime>

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2021-01-13 10:11

    You can use the Windows API Function GetTickCount() and compare the values at start and end. Resolution is in the 16 ms ballpark. If for some reason you need more fine-grained timings, you'll need to look at QueryPerformanceCounter.

    0 讨论(0)
  • 2021-01-13 10:21

    C++ works on many platforms. Why not use something that also works on many platforms, such as the Boost libraries.

    Look at the documentation for the Boost Timer Library

    I believe that it is a header-only library, which means that it is simple to setup and use...

    0 讨论(0)
提交回复
热议问题