tags:

views:

341

answers:

4

Is there anywhere in C# to perform timing operations with sub millisecond accuracy? I'm putting timing code in my software and everything is being returned as 0ms. I would like to know if there is a way of getting even finer granularity.

Addendum: is this the correct code to get sub millisecond timing?

timeSpan.TotalMilliseconds / 10

I'm still getting 0 as the elapsed time

+12  A: 

You could always try using QueryPerformanceCounter or the StopWatch class for a managed approach

tyranid
There is no reason to use QueryPerformanceCounter as of .NET 2.0. Stopwatch is built-in and does the exact same thing. The frequency of both timers is exactly the same.
Sam
Indeed but he didn't specifically state he was using .NET 2.0 :) Although then again I didn't specify that is was 2.0+ to be fair.
tyranid
@tyranid, Technically he didn't specify .NET either, he just said C#. Theoretically he could be using one of the other C# compilers that compiles to something else (I've seen ones that compile to JavaScript and to FVM bytecode).
Sam
touché I guess :)
tyranid
+8  A: 

Use System.Diagnostics.Stopwatch

Sam
+3  A: 

Usually I measure these kinds of scenarios by repeating the operation multiple times (as many as needed to get the milliseconds over a few dozen or hundred.

Then you can adjust and measure more easily.

John Weldon
+1  A: 

You could try measuring your performance in matter of Ticks instead of milliseconds. It will be much more accurate in terms of performance.

but I agree with Sam and Tyranid, use System.Diagnostics.StopWatch.

Khalid Abuhakmeh