8

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

deltanovember
  • 42,611
  • 64
  • 162
  • 244
  • 1
    You're doing it wrong, there's going to be way too many things impacting so short a timespan, like JIT, GC, thread context switching, other threads being busy, etc. You should scale up your problem, execute some thousand or tens of thousands of iterations on your code, time that. – Lasse V. Karlsen Feb 08 '10 at 22:26
  • You might consider using a profiler instead. There are several commercial offerings, and a free one at http://www.eqatec.com/tools/profiler – TrueWill Feb 08 '10 at 23:29

5 Answers5

16

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

tyranid
  • 13,028
  • 1
  • 32
  • 34
  • 6
    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. – Samuel Neff Feb 08 '10 at 22:01
  • 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 Feb 08 '10 at 22:38
  • @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). – Samuel Neff Feb 09 '10 at 19:27
11

Use System.Diagnostics.Stopwatch

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
3

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
  • 39,849
  • 11
  • 94
  • 127
1

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
  • 10,709
  • 10
  • 52
  • 75
1

I learned something new. Those Ticks are handy indeed. Complete example:

Stopwatch stopwatch = Stopwatch.StartNew();

// Run code to get duration of

long durationInTicks = stopwatch.ElapsedTicks;
Console.WriteLine($"Duration: {(decimal)durationInTicks / TimeSpan.TicksPerMillisecond:f3}ms");

You can also use stopwatch.ElapsedTicks inside the Console.WriteLine, but I do not know if that has any performance delays, that's why I first retrieve it and put it in a variable.

KoalaBear
  • 2,755
  • 2
  • 25
  • 29