Benchmarking with Stopwatch in C#
By FoxLearn 12/26/2024 7:36:04 AM 153
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.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
How to secure ASP.NET Core with NWebSec
11/07/2024
Spica Admin Dashboard Template
11/18/2024