C# > Diagnostics and Performance > Profiling and Analysis > Using Stopwatch for Timing Code

Using Stopwatch in a Using Statement: Ensuring Proper Resource Management

This snippet demonstrates how to use the `Stopwatch` class within a `using` statement. This approach ensures that the `Stopwatch` object is properly disposed of, even if exceptions occur during the timing process. While `Stopwatch` itself doesn't require disposal in the traditional sense (it doesn't hold unmanaged resources), using the `using` statement can improve code readability and make it easier to reason about resource management.

Code Example

This code creates a `Stopwatch` instance within a `using` statement. The `using` statement ensures that the `Stopwatch` object is disposed of at the end of the block, even if an exception is thrown. This is generally good practice, even if `Stopwatch` doesn't require explicit disposal because it helps maintain consistency and clarity in your code. The `try-catch-finally` block ensures that `stopwatch.Stop()` is always called, guaranteeing that the timer is stopped, and the elapsed time is captured, even if an exception occurs during the measured code block.

using System; using System.Diagnostics; 

public class StopwatchExample
{
    public static void Main(string[] args)
    {
        using (Stopwatch stopwatch = new Stopwatch())
        {
            stopwatch.Start();

            // Code block to be measured.
            try
            {
                for (int i = 0; i < 1000000; i++)
                {
                    // Some arbitrary operation.
                    double result = Math.Sqrt(i);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
            finally
            {
                stopwatch.Stop(); // Ensure the stopwatch is stopped even if an exception occurs.

                // Get the elapsed time as a TimeSpan value.
                TimeSpan ts = stopwatch.Elapsed;

                // Format and display the TimeSpan value.
                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                    ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);

                Console.WriteLine("RunTime " + elapsedTime);
            }
        }
        // The 'stopwatch' variable is now out of scope and effectively disposed of.
    }
}

Benefits of Using Statement

While the `Stopwatch` class itself doesn't implement `IDisposable` and doesn't require explicit disposal, using a `using` statement offers several advantages:

  • Readability: It clearly signals that the `Stopwatch`'s lifetime is limited to the scope of the `using` block.
  • Consistency: If you're working with other objects that do require disposal, using `using` consistently improves code maintainability.
  • Exception Handling: The `using` statement automatically handles the disposal, even if an exception occurs, preventing potential resource leaks (though this isn't a concern with `Stopwatch`).

Memory Footprint

The `Stopwatch` class has a relatively small memory footprint. It mainly holds the start and stop times (usually as ticks). Using a `using` statement doesn't significantly impact the memory footprint, but it does provide a more deterministic scope for the object's lifetime.

When to Use `using` with Stopwatch

While not strictly necessary for `Stopwatch`, using a `using` statement can be beneficial in the following scenarios:

  • When you want to clearly define the scope of the `Stopwatch` object.
  • When you are working in a codebase where consistent resource management practices are enforced.
  • For improved code readability and maintainability.

FAQ

  • Does the `Stopwatch` class implement `IDisposable`?

    No, the `Stopwatch` class does not implement the `IDisposable` interface. Therefore, it does not require explicit disposal using the `Dispose()` method.
  • Is it necessary to use a `using` statement with the `Stopwatch` class?

    No, it's not strictly necessary because `Stopwatch` doesn't implement `IDisposable`. However, using a `using` statement can improve code readability and make resource management more consistent, even if it doesn't have a direct impact on the `Stopwatch` itself.