Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accurately measure elapsed wall clock time in .NET

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).

like image 420
pauldoo Avatar asked Sep 24 '10 08:09

pauldoo


People also ask

What is wall time in %% time?

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.

What are used to measure the elapsed time of events?

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.

How do you calculate wall time?

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.

What is wall time Python?

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.


1 Answers

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.

like image 94
Jon Skeet Avatar answered Oct 28 '22 04:10

Jon Skeet