The Stopwatch class is a fundamental component of the .NET framework, specifically in the System.Diagnostics namespace. It provides a comprehensive set of methods and properties that enable developers to accurately measure time intervals in their applications. With its precise timing capabilities, the Stopwatch class proves invaluable when evaluating the efficiency of algorithms, identifying performance bottlenecks, and conducting performance optimizations.
Stopwatch Example – Console Application
The provided code is a simple example that demonstrates the usage of the Stopwatch class in C# Console Application to measure the time taken by a specific method.
internal class Program { static void Main(string[] args) { var timer = new Stopwatch(); timer.Start(); SomeMethod(); timer.Stop(); TimeSpan timeTaken = timer.Elapsed; string timeTakenLabel = "Time taken: " + timeTaken.ToString(@"m\:ss\.fff"); Console.WriteLine(timeTakenLabel); } private static void SomeMethod() { Thread.Sleep(new Random().Next(1000, 2000)); } }
The timer is started using the Start method, which initiates the time measurement. The SomeMethod method is called. This method simulates a time-consuming operation by pausing the execution for a random duration between 1,000 and 2,000 milliseconds (1 to 2 seconds) using the Thread.Sleep method. After the SomeMethod execution completes, the timer is stopped using the Stop method. The Elapsed property of the timer is accessed to retrieve the elapsed time as a TimeSpan object, which represents the duration between the Start and Stop calls. The timeTaken TimeSpan is converted to a formatted string representation using the ToString method with a custom format string (@”m\:ss\.fff”), which displays minutes, seconds, and milliseconds.