Benchmarking with Stopwatch in C#
By Tan Lee Published on Dec 26, 2024 279
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:
- Instantiate a new
Stopwatch
object. - Start the stopwatch explicitly.
- Stop the stopwatch explicitly after the task is complete.
- Output the elapsed time using the
Elapsed
property, which is aTimeSpan
.
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.
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Material Lite Admin Template
Nov 14, 2024
Toolbox Admin Responsive Tailwind CSS Admin Template
Nov 20, 2024
Carpatin Admin Dashboard Template
Nov 15, 2024