# 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?

Your clock code comes from #include <ctime> and OutputDebugString comes from #include <windows.h>.

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().

• This should be basic ABC for every game coder, since this is needed to write a proper game loop... Dec 22, 2012 at 14:20

I noticed you tagged your post SDL, so you can call SDL_GetTicks() which will return the number of ms since your program started. Print this to the console or a file at the start of the section you want to time and then print it at the end, calculate the difference between them and you've got your timing.

Or assign it to a variable at the start, then calculate the difference between the start and the current time at the end: SDL_GetTicks() - startTime, and print this to the console/file.

You could use a profiler. In the general case, a profiler will tell you where the slow parts of your program are. But it's not always helpful - enabling profiling generally slows your program down but does not slow time down, nor slow your graphics or other hardware down, so it can give a distorted picture.

It's also worth noting that you can't usefully time a simple, fast operation, because it will be too fast to measure accurately, and in a single run the effects of (e.g.) CPU caches may give a misleading picture.

If it's something big that takes, say, 50ms, then it's ok though.