How to Use Stopwatch in C#

Muhammad Maisam Abbas Feb 16, 2024
How to Use Stopwatch in C#

This tutorial will discuss methods to calculate elapsed time in C#.

Calculate Elapsed Time With the Stopwatch Class in C#

The Stopwatch class accurately measures the elapsed time in C#. The Stopwatch.Start() method starts the stopwatch, and the Stopwatch.Stop() method stops the stopwatch and calculate the elapsed time.

The following code example shows us how we can calculate the time taken by a piece of code to execute with the Stopwatch class in C#.

using System;
using System.Diagnostics;

namespace stopwatch {
  class Program {
    static void StopwatchUsingMethod() {
      var timer = new Stopwatch();
      timer.Start();
      for (int i = 0; i < 1000000000; i++) {
        int x = i * i + 1;
      }
      timer.Stop();

      TimeSpan timeTaken = timer.Elapsed;
      string foo = "Time taken: " + timeTaken.ToString(@"m\:ss\.fff");
      Console.WriteLine(foo);
    }
    static void Main(string[] args) {
      StopwatchUsingMethod();
    }
  }
}

Output:

Time taken: 0:03.226

In the above code, we created the instance of the Stopwatch class timer and calculated the time taken by the for loop to execute. We used the timer.Start() method to start the stopwatch and the timer.Stop() method to stop the stopwatch. We stored the elapsed time in an instance of the TimeSpan class with the timer.Elapsed property and converted it to a string variable with the ToString() function in C#.

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn