7

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))
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
uriDium
  • 13,110
  • 20
  • 78
  • 138

2 Answers2

10

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.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Joe
  • 122,218
  • 32
  • 205
  • 338
0

Ensure you're actually starting a Stopwatch and that you're using either Stopwatch.ElapsedMilliseconds or Stopwatch.Elapsed.TotalMilliseconds.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288