What is the most convenient way of accurately measuring elapsed wall clock time in .NET? I'm looking for something with microsecond accuracy if possible (10^-6 seconds).
Wall time, also called real-world time or wall-clock time, refers to elapsed time as determined by a chronometer such as a wristwatch or wall clock. (The reference to a wall clock is how the term originally got its name.) Wall time differs from time as measured by counting microprocessor clock pulses or cycles.
How do you calculate elapsed time? Calculating elapsed time can be done by measuring the time between the start and finish of an event. This can be done by the use of simple addition or subtraction.
Calculating the elapsed wall clock time of a program is helpful to determine how much time it actually takes for a program to complete. The easy method is to take the time the program ends and then subtract the time the program starts.
The wall-clock time is also called elapsed or running time. Compared to the CPU time, the wall-clock time is often longer because the CPU executing the measured program may also be executing other program's instructions at the same time.
System.Diagnostics.Stopwatch
is your best bet. However, the exact accuracy will depend on the hardware on the computer you're using, i.e. whether a high-resolution performance counter is available. (You can check that with the IsHighResolution
field.)
Sample use:
Stopwatch sw = Stopwatch.StartNew();
// Do stuff here
sw.Stop();
TimeSpan time = sw.Elapsed;
Note that if you use the ElapsedTicks
property, that's measured in timer ticks which is not the same as the ticks used in DateTime
and TimeSpan
. That's caught me out before now - which is why I always use ElapsedMilliseconds
or the Elapsed
property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With