newprint
newprint

Reputation: 7136

Measuring sub-second elapsed time of native C++ on Windows platform

What would be a good way to measure sub-second elapsed time of native C++ code on Windows Platform(I am working on Windows Vista, Visual Studio 2010)

I have tried using

#include <ctime>

int main()
{    
    clock_t start = clock();
    ... some code
    clock_t end = clock();
    double cpu_time = static_cast<double>(end - start)/CLOCKS_PER_SEC;
}

but cpu_time is always 0.

Thanks !

Upvotes: 2

Views: 706

Answers (2)

Logan Besecker
Logan Besecker

Reputation: 2761

Your code is all valid and working. If you're trying to time the execution of a particular piece of code, you should run it through a loop, as suggested by Xymostech. The main reason being:

  • Your code snippet will execute very fast. In some cases, executing the start, code-snippet, and end of your timer the same clock-tick. This will result in start holding the same value as end, causing cpu_time to equal zero.

however, there is also the added benefit of being able to calculate the average execution time over many iterations

Upvotes: 0

kol
kol

Reputation: 28678

You can use the QueryPerformanceFrequency and QueryPerformanceCounter WinAPI functions. Example

Upvotes: 2

Related Questions