Say I have a method Foo() and I want to measure the time in milliseconds it took to execute which type of Windows Performance Counter should I be using?
var stopwatch = new Stopwatch();
stopwatch.Start();
Foo();
stopwatch.Stop();
counter.RawValue = sto开发者_如何学编程pwatch.TotalMilliseonds;
Currently I'm using NumberOfItems64 but that persists the last value of the counter unless the new operation is performed. Is it desirable? Or should the counter go to zero as soon as the operation is done? Which counter type would you choose in this situation and why?
This sounds like a good candidate for AverageTimer32. See this SO answer for more details.
To add to previous answer, there is a very good article on both pre-made and custom-made performance counters on CodeProject..
I normally use Stopwatch, but I have also used p/invoke to kernel32.dll:
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
I have two methods called Start() and Stop():
public void Start()
{
Thread.Sleep(0);
QueryPerformanceCounter(out startTime);
}
public void Stop()
{
QueryPerformanceCounter(out stopTime);
}
To query the duration between calls to Start() and Stop():
public double Duration
{
get
{
return (double)(stopTime - startTime)*1000 / (double)freq;
}
}
Note that freq
is determined in the constructor:
public PerformanceTimer()
{
startTime = 0;
stopTime = 0;
if (QueryPerformanceFrequency(out freq) == false)
{
// not supported
throw new Win32Exception();
}
}
For my needs, I have not noticed much of a difference, although I suggest you try both to see what suits you.
Edit: I was able to locate the original code from MSDN. It appears there are some improvements made since .Net 1.1. The take-home message is that Microsoft claims that this method provides nanosecond accuracy.
An answer and a question:
Answer: Low-tech works for me. You want microseconds? Loop it 10^6 times and use your watch.
Question: Are you asking because you want to make your code faster? Then consider this.
精彩评论