Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ElapsedTicks * 10 000 not equal ElapsedMilliseconds for .NET's Stopwatch?

I am trying to performance test some code. I am using a stopwatch. When I output the number of milliseconds it always tells me 0 so I thought that I would try the number of ticks. I am seeing that the number of ticks is about 20 000 to 30 000. Looking at the MSDN at TimeSpan.TicksPerMillisecond it says that is 10 000 ticks per millisecond. In that case why are the elapsed milliseconds on my stopwatch not appearing as 2 or 3?

What am I missing? I have even outputed the result on the same line. This is what I get.

Time taken: 26856 ticks, 0 ms

And it is constant.

This is my code which I have running in a loop. I realize that I am creating a new stopwatch every time which isn't very efficient but I don't see how it could skew my results.

Dim SW = New Stopwatch()
SW.Reset()
SW.Start()
MethodCall()
SW.Stop()
Console.WriteLine(String.Format("Time to increase counters: {0} ticks, {1} ms", SW.ElapsedTicks, SW.ElapsedMilliseconds))
like image 538
uriDium Avatar asked Jun 09 '10 15:06

uriDium


People also ask

What is ElapsedMilliseconds?

Elapsed. TotalMilliseconds is a double that can return execution times to the partial millisecond while ElapsedMilliseconds is Int64 . e.g. a stopwatch at 0.0007 milliseconds would return 0, or 1234.56 milliseconds would return 1234 in this property.

What is Elapsed time in Stopwatch?

By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value.

What elapsed ticks?

A tick is the smallest unit of time that the Stopwatch timer can measure. Use the Frequency field to convert the ElapsedTicks value into a number of seconds. You can query the properties Elapsed, ElapsedMilliseconds, and ElapsedTicks while the Stopwatch instance is running or stopped.


1 Answers

Stopwatch ticks are different from DateTime Ticks.

The length of a Stopwatch tick depends on the Stopwatch frequency (one tick is one second divided by the frequency, as described in the MSDN documentation for Stopwatch.ElapsedTicks.

It could be argued that Stopwatch.ElapsedTicks was a poor choice of a name for this property because of the potential for confusion with DateTime ticks. I would have preferred something like ElapsedRawTicks, or some other suitable adjectival qualifier to hint that these are not standard Ticks.

like image 50
Joe Avatar answered Sep 28 '22 07:09

Joe