Measure execution time in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Diagnostics; using System.Threading; public class Example { public static void Main() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Thread.Sleep(5000); stopwatch.Stop(); Console.WriteLine("Elapsed Time is {0} ms", stopwatch.ElapsedMilliseconds); } } /* Output: Elapsed Time is 5000 ms */ |
To get the elapsed time as a TimeSpan value, we can do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System; using System.Diagnostics; using System.Threading; public class Example { public static void Main() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Thread.Sleep(5000); stopwatch.Stop(); TimeSpan ts = stopwatch.Elapsed; Console.WriteLine("Elapsed Time is {0:00}:{1:00}:{2:00}.{3}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds); } } /* Output: Elapsed Time is 00:00:05.14 */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Threading; public class Example { public static void Main() { DateTime start = DateTime.Now; Thread.Sleep(5000); DateTime end = DateTime.Now; TimeSpan ts = (end - start); Console.WriteLine("Elapsed Time is {0} ms", ts.TotalMilliseconds); } } /* Elapsed Time is 5005.1603 ms */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Threading; using System.Diagnostics; public class Example { public static void Main() { long start = Stopwatch.GetTimestamp(); Thread.Sleep(5000); long end = Stopwatch.GetTimestamp(); Console.WriteLine("Elapsed Time is {0} ticks", (end - start)); } } /* Elapsed Time is 50111533 ticks */ |
That’s all about measuring execution time in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)