Use Stopwatch class to measure time of execution of a method in .NET −
Stopwatch s = Stopwatch.StartNew();
Now set a function and use the ElapsedMilliseconds property to get the execution time in milliseconds −
s.ElapsedMilliseconds
Let us see the complete code −
Example
using System;
using System.IO;
using System.Diagnostics;
public class Demo {
public static void Main(string[] args) {
Stopwatch s = Stopwatch.StartNew();
display();
for (int index = 0; index < 5; index++) {
Console.WriteLine("Time taken: " + s.ElapsedMilliseconds + "ms");
}
s.Stop();
}
public static void display() {
Console.WriteLine("Demo function!");
}
}Output
Demo function! Time taken: 15ms Time taken: 16ms Time taken: 16ms Time taken: 16ms Time taken: 16ms