Measure Execution Time of Code in C#

measure execution time

Tags | calculate execution time in c#, how to find execution time in c#, how to measure execution time in c#, Measure Execution Time in C#, stopwatch c# example

How to calculate execution time of a method in C#

Sometimes we 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. In this article, I will explain best methods to measure the execution time of a complete c# program or a part of it with better accuracy.

  • Measure execution time using Stopwatch
  • Calculate execution time using DateTime

Measure Execution Time Using Stopwatch

Consider a simple c# program to find the 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 – sum=[n*(n+1)]/2
  2. using loop

Find the source code below:

The output of the program looks like:

measure execution time 2

Download Source Code

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# is using DateTime.

Issue: less Precision due to background works.

Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.


Please enter your comment!
Please enter your name here