A lesser-used aspect of DateTime
calculations in .NET is Stopwatch type that is
designed to assist programmers to calculate the runtime performance of a piece
of code. Most programmers tend to use DateTime.Now
and DateTime.UtcNow before and after a piece of code
to find the duration of time that it takes to execute.
Stopwatch relies on a public
static method called GetTimeStamp which works in two
modes. If it’s not used in high resolution mode, it applies DateTime.UtcNow,
otherwise it applies QueryPerformanceCounter from
Windows API (listing 3) that I will discuss in the next section.
Listing 3: GetTimeStamp implementation in Stopwatch
public static long GetTimestamp()
{
if (Stopwatch.IsHighResolution)
{
long result = 0L;
SafeNativeMethods.QueryPerformanceCounter(out result);
return result;
}
return DateTime.UtcNow.Ticks;
}