Stopwatch
This .NET type measures time elapsed. It is useful for benchmarks in code optimization. And it can perform routine performance monitoring.
Stopwatch
, found in System.Diagnostics
, is useful in many programs. It provides accurate measurement of time elapsed, and helps with benchmarking.
Stopwatch
is ideal for timing any operation. The code includes the "System.Diagnostics
" namespace at the top. This is where the Stopwatch
class
is defined.
Stopwatch
to store the current time. It queries the OS to find the current tick count of the system.Stopwatch
. This tells the Stopwatch
to capture the current tick count of the system.Stopwatch
is a TimeSpan
struct
, which overrides the ToString
method.using System; using System.Diagnostics; using System.Threading; // Create new stopwatch. Stopwatch stopwatch = new Stopwatch(); // Begin timing. stopwatch.Start(); // Do something. for (int i = 0; i < 1000; i++) { Thread.Sleep(1); } // Stop timing. stopwatch.Stop(); // Write result. Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);Time elapsed: 00:00:01.0001477
Stopwatch
can handle short
timings of only a few milliseconds. For longer timings, we want to display hours, minutes and seconds. Nanoseconds aren't important here.
string
. We must escape the ":" characters in the format string
. We use hh, mm and ss.using System; using System.Diagnostics; class Program { static void Main() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // ... This takes 10 seconds to finish. for (int i = 0; i < 1000; i++) { System.Threading.Thread.Sleep(10); } // Stop. stopwatch.Stop(); // Write hours, minutes and seconds. Console.WriteLine("Time elapsed: {0:hh\\:mm\\:ss}", stopwatch.Elapsed); } }Time elapsed: 00:00:10
StartNew
For benchmarks or diagnostics code, you probably will prefer the StartNew
method. This uses a creational design pattern to return a new instance from a static
type method.
Stopwatch
. We show the var
syntax, which is a shorthand for the type declaration.class Program { static void Main() { // Create new stopwatch. var stopwatch = System.Diagnostics.Stopwatch.StartNew(); // Do something (omitted). // Stop timing. stopwatch.Stop(); // Write the results (omitted). } }
ElapsedTicks
This is internally a readonly
signed System.Int64
value. When you capture ElapsedTicks
, you have to manually do the calculations to convert the values to seconds.
Stopwatch
with StartNew
, and then captures the ElapsedTicks
long property twice.Console.WriteLine
here was the most expensive operation. It took 7081 ticks.ElapsedTicks
value from Stopwatch
is not normally the same as the DateTime.Ticks
value.Stopwatch
ticks are far more accurate when the IsHighResolution
property is true. Otherwise, they are equivalent.using System; using System.Diagnostics; class Program { static void Main() { // Create a new Stopwatch. var stopwatch = Stopwatch.StartNew(); // Capture the elapsed ticks and write them to the console. long ticks1 = stopwatch.ElapsedTicks; Console.WriteLine(ticks1); // Capture the ticks again. // ... This will be a larger value. long ticks2 = stopwatch.ElapsedTicks; Console.WriteLine(ticks2); } }11 7092
Restart()
sets the timer information to zero. It then calls Start again on the Stopwatch
, so you can time further statements. This is like calling Reset and Start.
Stopwatch
.using System; using System.Diagnostics; using System.Threading; class Program { static void Main() { Stopwatch stop = Stopwatch.StartNew(); Thread.Sleep(1000); stop.Restart(); Thread.Sleep(1000); Console.WriteLine(stop.ElapsedMilliseconds); } }1000
Stopwatch
usage has a performance impact. The Stopwatch
class
is slower than many operations. This applies when you are using Stopwatch
for routine monitoring.
Stopwatch
is more expensive than simple operations in .NET. Stopwatch
itself can become a performance problem.using System; using System.Diagnostics; class Program { const int _max = 1000000; static void Main() { var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { var sw = Stopwatch.StartNew(); sw = null; } s1.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }600.64 ns
Stopwatch
has some static
properties and fields, including Frequency and IsHighResolution
. These determine the configuration of Stopwatch
, which depends on the system.
Stopwatch
uses per second. It is used to convert ElapsedTicks
to a figure in seconds.IsHighResolution
tells whether the Stopwatch
is using high resolution timing.Stopwatch.Frequency: 14318180 Stopwatch.IsHighResolution: True Stopwatch.GetTimestamp: 174412139895
IsRunning
This is only useful if your code uses Stop or Reset in unpredictable ways. For most micro-benchmarks, it is not necessary. Using the simplest logic for Stopwatch
is best.
Stopwatch
is a useful class
for performing diagnostics or benchmarks. Simple and powerful, it can lead to higher quality programs.