Monday, March 12, 2018

c++ - How can I measure the execution time of some code?


How can I capture how long something takes to complete and log it to the output window (in Visual Studio)?


Is there a special library for this?


clock_t start, end;
double cpuTime;

start = clock();


//....bit to be timed

end = clock();


cpuTime= (end - start) / (CLOCKS_PER_SEC);

OutputDebugString(TEXT("Time: %d", cpuTime));


This code might work but where does it come from? A special include?



Answer



Your clock code comes from #include and OutputDebugString comes from #include .


OutputDebugString will not print anything if there is no debugger available.


If you want platform independent code you might want to take a look at boost timers.


If you don't like boost and need nano precision on multiple platforms, the keyword on Windows is QueryPerformanceCounter and for Linux and BSD you want to use clock_gettime().


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...