How to Use Stopwatch in C# for Measuring Time
Use the
Stopwatch class from System.Diagnostics to measure elapsed time in C#. Start it with Start(), stop with Stop(), and get the elapsed time using Elapsed or ElapsedMilliseconds properties.Syntax
The Stopwatch class provides methods and properties to measure time intervals. Key parts include:
Start(): Begins timing.Stop(): Stops timing.Reset(): Clears the elapsed time.Elapsed: Gets the total elapsed time as aTimeSpan.ElapsedMilliseconds: Gets the elapsed time in milliseconds as along.
csharp
using System.Diagnostics; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // Code to time stopwatch.Stop(); TimeSpan elapsed = stopwatch.Elapsed; long milliseconds = stopwatch.ElapsedMilliseconds;
Example
This example shows how to measure the time taken to pause the program for 2 seconds using Thread.Sleep. It starts the stopwatch, waits, stops it, and prints the elapsed time.
csharp
using System; using System.Diagnostics; using System.Threading; class Program { static void Main() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Thread.Sleep(2000); // Pause for 2 seconds stopwatch.Stop(); Console.WriteLine($"Elapsed time: {stopwatch.ElapsedMilliseconds} ms"); } }
Output
Elapsed time: 2000 ms
Common Pitfalls
Common mistakes when using Stopwatch include:
- Not calling
Start()before measuring time. - Calling
Start()multiple times withoutReset(), which continues timing instead of restarting. - Using
ElapsedMillisecondsfor very short intervals whereElapsedTicksmight be more precise.
Always stop the stopwatch before reading elapsed time to get accurate results.
csharp
using System.Diagnostics; Stopwatch sw = new Stopwatch(); // Wrong: reading elapsed before starting Console.WriteLine(sw.ElapsedMilliseconds); // Outputs 0 sw.Start(); // Do work sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); // Correct usage // To restart timing sw.Reset(); sw.Start();
Output
0
[Elapsed time after Stop() call]
Quick Reference
| Method/Property | Description |
|---|---|
| Start() | Starts or resumes measuring elapsed time. |
| Stop() | Stops measuring elapsed time. |
| Reset() | Stops time and resets elapsed time to zero. |
| Restart() | Resets and starts measuring elapsed time. |
| Elapsed | Gets the elapsed time as a TimeSpan. |
| ElapsedMilliseconds | Gets the elapsed time in milliseconds. |
| ElapsedTicks | Gets the elapsed time in timer ticks (high precision). |
Key Takeaways
Use Stopwatch.Start() and Stopwatch.Stop() to measure elapsed time accurately.
Read elapsed time only after stopping the stopwatch for correct results.
Reset the stopwatch before reusing it to avoid accumulating time.
ElapsedMilliseconds gives time in ms; use Elapsed for TimeSpan details.
Stopwatch is ideal for performance timing and measuring code execution duration.