How to Measure Execution Time in C#

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

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.

Create an object of stopwatch

Step 2

Define both functions using equation and loop iteration, it will return time taken by these methods in milliseconds

Using equation

Using loop iteration

Call these functions from main method

Output of the program looks like

measure execution time in C# : Output
Output

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

Issue : less Precision due to background works

 

2 thoughts on “How to Measure Execution Time in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment moderation is enabled. Your comment may take some time to appear.