C# sub millisecond timing
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开发者_StackOverflow社区 millisecond timing?
timeSpan.TotalMilliseconds / 10
I'm still getting 0 as the elapsed time
You could always try using QueryPerformanceCounter or the StopWatch class for a managed approach
Use System.Diagnostics.Stopwatch
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.
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.
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.
精彩评论