bpeikes
bpeikes

Reputation: 3685

Simple profiling of single C++ function in Windows

There are times, particularly when I'm writing a new function, where I would like to profile a single piece of code but a full profile run is not really necessary, and possibly too slow.

I'm using VS 2008 and have used the AMD profiler on C++ with good results, but I'm looking for something a little more lightweight.

What tools do you use to profile single functions? Perhaps something that is a macro which gets excluded when your not in DEBUG mode. I could write my own, but I wanted to know if there were any built in that I'm missing. I was thinking something like:

void FunctionToTest()
{
    PROFILE_ENTER("FunctionToTest")
    // Do some stuff
    PROFILE_EXIT()
}

Which would simply print in the debug output window how long the function took.

Upvotes: 1

Views: 727

Answers (3)

Mike Dunlavey
Mike Dunlavey

Reputation: 40649

If I want to get maximum speed from a particular function, I wrap it in a nice long-running loop and use this technique. I really don't care too much about the time it takes. That's just the result. What I really need to know is what must I do to make it take less time. See the difference? After finding and fixing the speed bugs, when the outer loop is removed, it flies.

Also I don't follow the orthodoxy of only tuning optimized code, because that assumes the code is already nearly as tight as possible. In fact, in programs of any significant size, there is usually stupid stuff going on, like calling a subfunction over and over with the same arguments, or new-ing objects repeatedly, when prior copies could be re-used. The compiler's optimizer might be able to clean up some such problems, but I need to clean up every one, because the ones left behind will dominate. What it can do is make them harder to find, by scrambling the code. When I've gotten all the stupid stuff out (making it much faster), then I turn on the optimizer.

You might think "Well I would never put stupid stuff in my code." Right. And you'd never put in bugs either. None of us try to make mistakes, but we all do, if we're working.

Upvotes: 1

ogni42
ogni42

Reputation: 1276

Measure the time - which the code in the link does too - using either clock() or one of the OS provided high resolution timers. With C++11 you can use the timers from the <chrono> header.

Please note, that you should always measure in Release build not Debug build, to get proper timings.

Upvotes: 0

Chris Sterling
Chris Sterling

Reputation: 99

This code by Jeff Preshing should do the trick:-

http://preshing.com/20111203/a-c-profiling-module-for-multithreaded-apis

Upvotes: 0

Related Questions