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:
- 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 fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Dashboardkit Bootstrap
11/13/2024
Material Lite Admin Template
11/14/2024
Stisla Admin Dashboard Template
11/18/2024