When I just posted the source code of the Dependency Property Serialization sample, I realized it included a small piece of source code that might come in handy from time to time:
A very basic, but rather exact profiler. It uses QueryPerformanceCounter. Perhaps I shouldn’t even call this profiler, because a profiler typically keeps track of the parts of code it measures. So let’s call it a precise stopwatch. Well, anyways, here’s the code:
using System.Runtime.InteropServices;
namespace SimpleProfiler
{
public class Profiler
{
long mFrequency;
long mAccumulatedTime;
long mStartTime;
long mEndTime;
long mLastTime;
bool mInitialized = false;
bool mRunning = false;
public Profiler()
{
mInitialized = QueryPerformanceFrequency(out mFrequency);
}
public bool StartMeasure()
{
if (mInitialized && !mRunning)
{
mRunning = true;
return QueryPerformanceCounter(out mStartTime);
}
return false;
}
public bool StopMeasure()
{
if (mInitialized && mRunning)
{
mRunning = false;
bool bSuccess = QueryPerformanceCounter(out mEndTime);
if (bSuccess)
{
mLastTime = mEndTime - mStartTime;
mAccumulatedTime += mLastTime;
return true;
}
}
return false;
}
public double GetLastTime()
{
return (double)((double)mLastTime / (double)mFrequency);
}
public double GetAccumulatedTime()
{
return (double)((double)mAccumulatedTime / (double)mFrequency);
}
[DllImport("kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long count);
[DllImport("kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long frequency);
}
}
which is also contained in the source code for the previous article.

