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
let’s find out time taken by these two methods, Actually there are few methods to get the job done.Using the Stopwatch class is the most easiest and recommended one. Stopwatch is a c# library class which is made for this purpose.
Add namespace System.Diagnostics for Stopwatch Class.
Create an object of stopwatch
Define both functions using equation and loop iteration, it will return time taken by these methods in milliseconds
Call these functions from main method
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#
Issue : less Precision due to background works