In C#, the System.Diagnostics namespace of System.Runtime.dll has the Stopwatch class which can be used to accurately measure the time taken for code execution.
Measure the code execution time using Stopwatch instance in C#:
A Stopwatch instance can be used to measure elapsed time for one interval or the total of elapsed time across multiple intervals. In the below example you can see how to use Stopwatch scenario where the Start method is called first, then eventually Stop method is called, and then Elapsed property is checked for the time taken to execute the piece of code.
The following example demonstrates how to use the Stopwatch class to determine the execution time for an application of a for loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
using System; using System.IO; using System.Text; using System.Diagnostics; namespace ConsoleApplication1 { public class Program { public static void Main() { Stopwatch sp = new Stopwatch(); //Start the stopwatch sp.Start(); for (int i = 0; i < 5000; i++) { //Do something. } //Stop the stopwatch. sp.Stop(); //Read the total execution time into TimeSpan object. TimeSpan ts = sp.Elapsed; //Read the total execution time measured in miliseconds. long lElpTimeMs = sp.ElapsedMilliseconds; //Read the total execution time measured in timer ticks long lElpTicks = sp.ElapsedTicks; //Reset the stopwatch that will clear/reset the timer information to 0. if (sp.IsRunning) { sp.Reset(); } //Or - Restart the stopwatch which does the stopwatch Reset() and stopwatch Start() internally sp.Restart(); //Print measured time string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Total Elapsed Time: " + elapsedTime); Console.WriteLine("Total Elalsed time in Miliseconds", lElpTimeMs.ToString()); Console.WriteLine("Total Elalsed time in Timer Ticks", lElpTicks.ToString()); } } } |
– Article ends here –