Reputation: 44051
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
Upvotes: 9
Views: 2978
Reputation: 2948
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.
Upvotes: 2
Reputation: 10839
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.
Upvotes: 2
Reputation: 40749
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.
Upvotes: 3
Reputation: 13318
You could always try using QueryPerformanceCounter or the StopWatch class for a managed approach
Upvotes: 16