When I execute the following program and look at the performance counter the results don\'t make sense to me. The average value is zero and the min/max values are ~0.4 when I w
This is an old thread, but I thought I'd chime in. I was told by someone from Microsoft that I shouldn't use TimeSpan
, StopWatch
, or DateTime
when working with Performance Counters. Instead, he recommended adding the following native method to my project:
internal static class NativeMethods
{
[DllImport("Kernel32.dll")]
public static extern void QueryPerformanceCounter(ref long ticks);
}
When incrementing a counter, he recommended doing so like this:
public void Foo()
{
var beginTicks = 0L;
var endTicks = 0L;
NativeMethods.QueryPerformanceCounter(ref beginTicks);
// Do stuff
NativeMethods.QueryPerformanceCounter(ref endTicks);
this.Counter.IncrementBy(endTicks - beginTicks);
this.BaseCounter.Increment();
}
The System.Diagnostics API contains a pretty subtle source of great confusion: System.Diagnostics 'ticks' are not the same as DateTime or TimeSpan 'ticks'!
If you use StopWatch.ElapsedTicks instead of StopWatch.Elapsed.Ticks, it should work.
The documentation contains more information about this.
Mark Seemann explained the confusing source of the problem but I would like to provide a little bit of additional information.
If you want to set your AverageTimer32
performance counter from a TimeSpan
and not a Stopwatch
you can perform the following conversion:
var performanceCounterTicks = timeSpan.Ticks*Stopwatch.Frequency/TimeSpan.TicksPerSecond;
averageTimerCounter.IncrementBy(performanceCounterTicks);
averageTimerCounterBase.Increment();