views:

69

answers:

3

An expert in highly optimized code once told me that an important part of his strategy was the availability of extremely high performance timers on the CPU. Does anyone know what those are and how one can access them to test various code optimizations?

While I am interested regardless, I also wanted to ask whether it is possible to access them from something higher than assembly (or with only a little assembly) via visual studio C++?

+3  A: 

That is going to be platform dependent, but since you mention Visual Studio, I will assume windows.

You need QueryPerformanceCounter in win32. You can use StopWatch in .Net as well.

Re: StopWatch resolution
Directly from the linked documentation

Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

In other words, it can be high or low resolution. In the case that it is low and you need high, you would pinvoke the win32 Timer functions (QueryPerformanceCounter etc)

BioBuckyBall
I thought StopWatch only used the usual times windows offers, e.g. with a resolution of about 10-15ms (which I would guess is really updated with each thread switch). Am I wrong about StopWatch being only a fairly course timer?
John Robertson
@John Robertson: see update
BioBuckyBall
Oh shoot, you are right, it does have those fields. I had forgotten but was familiar with StopWatch which I have used in the past so I didn't look over it more carefully. My apologies.
John Robertson
+2  A: 

QueryPerformanceCounter() and related functions in Win32 use the high performance timers built into most modern Intel chips.

dthorpe
+1  A: 

The accuracy of your timer depends entirely on your hardware. If your hardware can't measure something smaller than a microsecond, it's impossible to be more accurate than to the nearest microsecond.

In my experience, though, I've never needed better accuracy than milliseconds for performance measurement. Unless you're building a micro-controller where every assembly instruction is critical to your speed, any noticeable speed differential is going to be on the order of seconds, not microseconds. And if you're using Visual C++, it's unlikely that you'd be working on a micro-controller.

Brian S
I have a lot of data coming in very quickly and it needs to be marked with accurate arrival time indicators. A microsecond *might* work, but I am dubious, 10 is out of the question. Of course typing this I realize that threading issues alone prevent you from getting better than 10 microseconds your thread will be swapped out for periods that long. Hmmm, I wonder how wireshark gets those microsecond arrival times.
John Robertson