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
- Must read jQuery Wikipedia Tooltip Plugin for Texts and Keywords
- HTML Input Text Autocomplete jQuery
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:-
- using equation – sum=[n*(n+1)]/2
- using loop
Find the source code below:
static Stopwatch timer = new Stopwatch();
static void Main(string args)
Console.WriteLine("Time taken(ms) : " + FindSumByEqn(100000));
Console.WriteLine("Time taken(ms) : " + FindSumUsingLoop(100000));
static double FindSumByEqn(int n)
timer.Reset();//reset timer to 0
Console.WriteLine("Sum : " + (n * (n + 1) / 2).ToString());
//get time elapsed in milliseconds
static double FindSumUsingLoop(int n)
int sum = 0;
for (int i = 1; i <= n; i++)
sum += i;
Console.WriteLine("Sum : " + sum.ToString());
The 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# is using DateTime.
DateTime begin = DateTime.UtcNow;
//Do your work here
Console.WriteLine("Time taken(ms) : " +
(DateTime.UtcNow - begin).TotalMilliseconds);
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.