C# Reference ยท Numbers and Math
The Stopwatch class
Reference for System.Diagnostics.Stopwatch: Start, Stop, Restart, Elapsed, GetTimestamp and GetElapsedTime for accurate timing of code in C# and .NET.
Stopwatch (namespace System.Diagnostics) measures elapsed time using the highest-resolution timer the operating system offers. It is the right tool for timing code, measuring how long a request took, or enforcing a time budget. It is not affected by changes to the system clock, unlike subtracting two DateTime.Now values.
A stopwatch accumulates time while it is running. You can start and stop it several times and the elapsed time adds up. Stopwatch.StartNew() creates and starts one in a single call.
var sw = Stopwatch.StartNew(); DoWork(); sw.Stop(); Console.WriteLine(sw.Elapsed);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class Stopwatch { public Stopwatch(); public static Stopwatch StartNew(); public void Start(); public void Stop(); public void Reset(); public void Restart(); public bool IsRunning { get; } public TimeSpan Elapsed { get; } public long ElapsedMilliseconds { get; } public long ElapsedTicks { get; } public static readonly long Frequency; public static readonly bool IsHighResolution; public static long GetTimestamp(); public static TimeSpan GetElapsedTime(long startingTimestamp); public static TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp); }
| Name | Description |
|---|---|
Start() |
Starts or resumes measuring. Calling it on a running stopwatch does nothing. |
Stop() |
Stops measuring but keeps the accumulated time. |
Reset() |
Stops the stopwatch and sets the elapsed time to zero. |
Restart() |
Sets the elapsed time to zero and starts measuring. |
Elapsed |
Total elapsed time as a TimeSpan. Can be read while running. |
ElapsedMilliseconds |
Total elapsed time in whole milliseconds (truncated). |
ElapsedTicks |
Elapsed time in stopwatch ticks, whose length is 1 / Frequency seconds. These are not the same as TimeSpan ticks. |
Frequency |
Number of stopwatch ticks per second on this machine. |
GetTimestamp() |
Returns the current raw timestamp in stopwatch ticks. |
GetElapsedTime(start[, end]) |
Converts the difference between two timestamps (end defaults to now) into a TimeSpan. Available since .NET 7. |
Errors: none of the members throw for normal use.
Usage notes
- Print or compare, do not assume. Timings vary between runs and machines, so tests should never assert exact values. Compare against generous bounds.
- Stopwatch ticks are not
TimeSpanticks. UseElapsedorGetElapsedTimefor aTimeSpan, or multiplyElapsedTicksby1.0 / Stopwatch.Frequencyto get seconds. GetTimestamp()plusGetElapsedTime()allocates nothing. This avoids creating aStopwatchobject and suits hot paths such as logging or metrics.- Not thread-safe. Do not call
StartandStopon one instance from several threads without your own locking. - Microbenchmarks mislead. The first run includes JIT compilation, and the optimizer may remove code whose result is never used. Run the work several times and use a benchmarking library for serious measurements.
- Wall-clock time only. The stopwatch measures real elapsed time, including time your thread spent waiting, not CPU time.
- Do not use it for dates. For "what time is it" use
DateTimeorDateTimeOffset. For code that must be testable, wrap time inTimeProvider.
Related
- DateTime, TimeSpan, Task.Delay
- Lessons: Dates and times, Performance basics