Benchmarking with Stopwatch in C#
By FoxLearn 12/26/2024 7:36:04 AM 117
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Motiv MUI React Admin Dashboard Template
11/19/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024