Measure execution time in C#

The Stopwatch class is specifically designed to measure elapsed time and may (if available on your hardware) provide good granularity/accuracy using an underlying high-frequency hardware timer. So this seem the best choice.

The IsHighResolution property can be used to determine whether high resolution timing is available. Per the documentation, this class offers a wrapper on the ‘best available’ Win32 APIs for accurate timing:

Specifically, the Frequency field and
GetTimestamp method can be used in
place of the unmanaged Win32 APIs
QueryPerformanceFrequency and
QueryPerformanceCounter.

There is detailed background on those Win32 APIs [here] and in linked MSDN docs 2.

High-Resolution Timer

A counter is a general term used in
programming to refer to an
incrementing variable. Some systems
include a high-resolution performance
counter that provides high-resolution
elapsed times.

If a high-resolution performance
counter exists on the system, you can
use the QueryPerformanceFrequency
function to express the frequency, in
counts per second. The value of the
count is processor dependent. On some
processors, for example, the count
might be the cycle rate of the
processor clock.

The QueryPerformanceCounter function
retrieves the current value of the
high-resolution performance counter.
By calling this function at the
beginning and end of a section of
code, an application essentially uses
the counter as a high-resolution
timer. For example, suppose that
QueryPerformanceFrequency indicates
that the frequency of the
high-resolution performance counter is
50,000 counts per second. If the
application calls
QueryPerformanceCounter immediately
before and immediately after the
section of code to be timed, the
counter values might be 1500 counts
and 3500 counts, respectively. These
values would indicate that .04 seconds
(2000 counts) elapsed while the code
executed.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)