Benchmarking with Stopwatch in C#

By FoxLearn 12/26/2024 7:36:04 AM   67
In this article, I’ll explain how to track time in a .NET application using the basic Stopwatch class.

The Stopwatch class provides methods and properties for accurately measuring elapsed time.

Basics of Using Stopwatch

// method 1
var stopwatch = new Stopwatch();
stopwatch.Start();
DoSomething();
stopwatch.Stop();
Console.WriteLine("Method #1 Total seconds: {0}", stopwatch.Elapsed.TotalSeconds);

To use the Stopwatch class, follow these four simple steps:

  1. Instantiate a new Stopwatch object.
  2. Start the stopwatch explicitly.
  3. Stop the stopwatch explicitly after the task is complete.
  4. Output the elapsed time using the Elapsed property, which is a TimeSpan.

Creating a Simple Abstraction

To make things cleaner and more reusable, let’s create an abstraction that simplifies the process. The goal is to make the code more compact and reusable without losing any of the functionality.

// method 2
using (Benchmark.Start("Method #2")) {
    DoSomething();
}
// Reusable Stopwatch Wrapper
public class Benchmark : IDisposable
{
    private Stopwatch _watch;
    private string _name;

    public static Benchmark Start(string name)
    {
        return new Benchmark(name);
    }

    private Benchmark(string name)
    {
        _name = name;
        _watch = new Stopwatch();
        _watch.Start();
    }

    #region IDisposable implementation

    // Stops the stopwatch and prints the elapsed time.
    public void Dispose()
    {
        _watch.Stop();
        Console.WriteLine("{0} Total seconds: {1}", _name, _watch.Elapsed.TotalSeconds);
    }

    #endregion
}

In summary, the Stopwatch class is a great tool for measuring execution time in .NET, and by wrapping it in an abstraction like the Benchmark class, you can simplify your code and make performance tracking more efficient.