Introduction
Sometimes we developers may have more than one way to do a single task. In those cases we can choose the best method based on their execution time. The article covers best methods to measure execution time of a complete c# program or a part of it with better accuracy.
Measure Execution Time Using Stopwatch
Consider a simple c# program to find sum of first n whole numbers (1,2,3 ..etc) starting from 1, where n is the number of terms.
it can be done in two ways
1.using equation
1 |
sum=[n*(n+1)]/2 |
2.using loop
let’s find out time taken by these two methods, Actually there are few methods to get the job done.Using the is the most easiest and recommended one. Stopwatch is a c# library class which is made for this purpose.
Step 1
Add namespace System.Diagnostics for Stopwatch Class.
1 2 |
using System.Diagnostics |
Create an object of stopwatch
1 |
static Stopwatch timer = new Stopwatch(); |
Step 2
Define both functions using equation and loop iteration, it will return time taken by these methods in milliseconds
Using equation
1 2 3 4 5 6 7 8 9 |
static double FindSumByEqn(int n) { timer.Reset();//reset timer to 0 timer.Start();//start timer Console.WriteLine("Sum : " + (n * (n + 1) / 2).ToString()); timer.Stop();//Stop timer //get time elapsed in milliseconds return timer.Elapsed.TotalMilliseconds; } |
Using loop iteration
1 2 3 4 5 6 7 8 9 10 11 |
static double FindSumUsingLoop(int n) { timer.Reset(); timer.Start(); int sum = 0; for (int i = 1; i <= n; i++) sum += i; Console.WriteLine("Sum : " + sum.ToString()); timer.Stop(); return timer.Elapsed.TotalMilliseconds; } |
Call these functions from main method
1 2 3 4 5 6 7 8 |
static void Main(string[] args) { Console.WriteLine("-Using Equation-"); Console.WriteLine("Time taken(ms) : " + FindSumByEqn(100000)); Console.WriteLine("-Using Loop-"); Console.WriteLine("Time taken(ms) : " + FindSumUsingLoop(100000)); Console.ReadKey(); } |
Output of the program looks like
From the output it is clear that Equation method is 5x faster than loop method.
Like this we can measure execution time taken by a c# program using Stopwatch Class.
Other Methods to Measure Execution Time in C#
1.Using DateTime
1 2 3 4 5 |
DateTime begin = DateTime.UtcNow; //Do your work here Console.WriteLine("Time taken(ms) : " + (DateTime.UtcNow - begin).TotalMilliseconds); |
Issue : less Precision due to background works
Nice one. Didnt know an inbuilt class “Stopwatch” existed!!!.
Thanks..
Thanks for the comment, I’m glad you enjoyed it