Friday, May 24, 2013

Best way to measure execution time in .Net

Sometimes you need to measure how long some code takes to run. This is useful for benchmarking or even comparison of different algorithms. There are three main ways of doing this.

The first one is by reading DateTime.UtcNow before you start and after you finish. This is quite fast, however its granularity is quite low (around 10ms.) If you want to measure something which takes less than that, simply run it thousands of times, and then divide by the number of executions.

The second approach is by using a StopWatch. You simply create a StopWatch object, call the Start() method, and then the Stop() method. Then read the Elapsed value. However this is known to be unreliable due to bugs in the BIOS on multi-processor systems. It is also time consuming in itself.

The third (and my favourite) way is by using Process.TotalProcessorTime.
You first call

TimeSpan start = Process.GetCurrentProcess().TotalProcessorTime;


and then

TimeSpan finish = Process.GetCurrentProcess().TotalProcessorTime;

This is the ideal way because it actually measure how long your process has made use of the CPU. However, it also has the worst performance.

No comments: