Measure time, milliseconds or microseconds for Windows C++
You can use the standard C++ <chrono>
library:
#include <iostream>
#include <chrono>
// long operation to time
long long fib(long long n) {
if (n < 2) {
return n;
} else {
return fib(n-1) + fib(n-2);
}
}
int main() {
auto start_time = std::chrono::high_resolution_clock::now();
long long input = 32;
long long result = fib(input);
auto end_time = std::chrono::high_resolution_clock::now();
auto time = end_time - start_time;
std::cout << "result = " << result << '\n';
std::cout << "fib(" << input << ") took " <<
time/std::chrono::milliseconds(1) << "ms to run.\n";
}
One thing to keep in mind is that using <chrono>
enables type safe, generic timing code but to get that benefit you have use it a bit differently than you would use dumb, type-unsafe timing libraries that store durations and time points in types like int
. Here's an answer that explains some specific usage scenarios and the differences between using untyped libraries and best practices for using chrono: https://stackoverflow.com/a/15839862/365496
The maintainer of Visual Studio's standard library implementation has indicated that the low resolution of high_resolution_clock
has been fixed in VS2015 via the use of QueryPerformanceCounter()
.
You need to use the QPC/QPF APIs to get compute the execution time. Invoke the code you want to between calls to QueryPerformanceCounter and then use QueryPerformanceFrequency to convert it from cycles to microseconds.
LARGE_INTEGER nStartTime;
LARGE_INTEGER nStopTime;
LARGE_INTEGER nElapsed;
LARGE_INTEGER nFrequency;
::QueryPerformanceFrequency(&nFrequency);
::QueryPerformanceCounter(&nStartTime);
SomethingToBeTimed();
::QueryPerformanceCounter(&nStopTime);
nElapsed.QuadPart = (nStopTime.QuadPart - nStartTime.QuadPart) * 1000000;
nElapsed.QuadPart /= nFrequency.QuadPart;
References: http://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx
You're looking for QueryPerformanceCounter
and related functions.