Calculate the execution time of a method in C#


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

 Live Demo

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

553 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements