How to measure program execution time in C#

By | 10:04 AM 1 comment
Tip showing how to measure time taken by a C# program using the class Stopwatch.


Stopwatch class provides a set of methods and properties that you can use to accurately measure elapsed time-by msdn
//don't forget to use namespace System.Diagnostics
using System.Diagnostics;
//creating object of Stopwatch
Stopwatch myTimer = new Stopwatch();
//strats timer
myTimer.Start();
//your program goes here
//loop to add numbers between 0 and 10000
int x = 0;
for (int i = 0; i < 10000; i++)
{
   x += i;
}
//stop timer after specific code under evaluation
myTimer.Stop();
//print time elapsed by the code inbetween Start() and Stop() methods.
Console.WriteLine("time elapsed :"+myTimer.Elapsed);

output for above code snippet was

Home

1 comment: