This post will discuss how to measure the execution time of a code snippet in C#.

1. Using Stopwatch Class

The Stopwatch class from System.Diagnostics namespace is used to measure elapsed time accurately. The following example demonstrates how to measure the execution time using the Stopwatch class.

Download  Run Code

 
To get the elapsed time as a TimeSpan value, we can do like:

Download  Run Code

2. Using DateTime.Now() method

Alternatively, we can get the total elapsed time in milliseconds using DateTime.Now. Note that this solution lacks the high-performance measurement of the Stopwatch class.

Download  Run Code

3. Using Stopwatch GetTimestamp() method

Stopwatch GetTimestamp() method returns the current number of ticks of the underlying timer mechanism. 10,000 Ticks form a millisecond.

Download  Run Code

That’s all about measuring execution time in C#.