Updated on
In C#, we measure elapsed time with the Stopwatch class from the System.Diagnostics namespace. We call Stopwatch.StartNew(), run the code we care about, call Stop(), and read the result from the Elapsed property as a TimeSpan.
As software engineers, we know precision and performance matter, and measuring time helps us with both. We can use it to optimize code execution, benchmark algorithms, or track application performance.
Without further delay, let’s start!
Why Should We Use Stopwatch in C#?
In C#, we can use the Stopwatch class to determine our code’s execution time. We can use these findings to improve our algorithms’ performance, which is useful during performance optimization processes. For example, let’s use Start() and Stop() method calls to calculate elapsed time:
public static Stopwatch CreateRandomArray(int size)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
var array = new int[size];
for (int i = 0; i < size; i++)
array[i] = Random.Shared.Next();
stopWatch.Stop();
return stopWatch;
}
Our example calculates how long it takes to create a random integer array of a given size. It lives in a public static class StopWatchMethods, and so do the other two methods we write later. Every file that uses Stopwatch needs using System.Diagnostics; at the top.
On top of that, we can use the Stopwatch class to compare the runtime for different algorithms. These measurements can give us a first idea of how an algorithm behaves as its input grows.
Stopwatch only measures time. If we need to run code on a schedule instead, that’s a job for a timer.
How Do We Start, Stop, Reset and Restart a Stopwatch?
A Stopwatch is either running or stopped, and its IsRunning property tells us which. Start() begins measuring, and Stop() freezes the elapsed time without clearing it.
That second part catches people out. If we call Start() again after Stop(), the stopwatch doesn’t begin from zero. It keeps adding to the time it already has, so two Start() and Stop() pairs give us the total of both intervals.
For a fresh measurement, we have two methods. Reset() stops the stopwatch and sets the elapsed time to zero, and the stopwatch stays stopped. Restart() does the same and then starts measuring again, so it’s a shortcut for Reset() followed by Start().
Stopwatch.StartNew() creates an instance that is already running, which saves us a separate Start() call.
We can read the elapsed time at any point. While the stopwatch runs, the value keeps growing. Once it stops, the value stays put until we start or reset it again.
Using our example, let’s verify that our Stopwatch instance properties are of the correct types. We run these checks in an MSTest test project that references our console app:
var arraySize = 10; var stopWatch = StopWatchMethods.CreateRandomArray(arraySize); Assert.IsInstanceOfType(stopWatch, typeof(Stopwatch)); Assert.IsInstanceOfType(stopWatch.Elapsed, typeof(TimeSpan)); Assert.IsInstanceOfType(stopWatch.ElapsedMilliseconds, typeof(long)); Assert.IsInstanceOfType(stopWatch.ElapsedTicks, typeof(long));
To start with, we can use the Elapsed, ElapsedMilliseconds, and ElapsedTicks properties to determine our example’s execution time.
In some cases, we may want to check whether our Stopwatch instance is still running, and that’s where we can take advantage of the IsRunning property:
Assert.IsFalse(stopWatch.IsRunning);
In our case, we know that our instance is not running so it returns false.
Apart from properties, we can invoke some methods to manipulate how our Stopwatch instance works. For example, Reset() and Restart() methods have different use cases. The former stops the current interval measurement and sets the elapsed time to zero, while the latter does the same and then starts measuring again:
stopWatch.Reset(); Assert.AreEqual(TimeSpan.Zero, stopWatch.Elapsed); Assert.IsFalse(stopWatch.IsRunning); stopWatch.Restart();
After invoking the Restart() method, we can now test that our Stopwatch instance is running:
Assert.IsTrue(stopWatch.Elapsed > TimeSpan.Zero); Assert.IsTrue(stopWatch.IsRunning);
Lastly, after invoking the Stop() method, we can verify that our Stopwatch instance is not running:
stopWatch.Stop(); Assert.IsFalse(stopWatch.IsRunning);
Let’s see the Start() after Stop() behavior in action. We measure two 100-millisecond sleeps and leave a third one outside the stopwatch:
public static Stopwatch MeasureTwoIntervals()
{
var stopWatch = Stopwatch.StartNew();
Thread.Sleep(100);
stopWatch.Stop();
Thread.Sleep(100);
stopWatch.Start();
Thread.Sleep(100);
stopWatch.Stop();
return stopWatch;
}
When we print ElapsedMilliseconds, the time between the two intervals is missing, as expected. The value changes on every run, and this is what we got on ours:
Two measured intervals: 214 ms
We slept for 200 milliseconds inside the stopwatch, and it reports a bit more because Thread.Sleep() doesn’t wake up exactly on time. The operating system lines the wait up with its own clock ticks, so the actual wait can differ a little from what we asked for.
Now that we have verified our properties and methods, let’s invoke our CreateRandomArray() method in our Program.cs file:
var stopWatch = StopWatchMethods.CreateRandomArray(1000);
Console.WriteLine($@"Elapsed Time: {stopWatch.Elapsed}
Elapsed Milliseconds: {stopWatch.ElapsedMilliseconds}
Elapsed Ticks: {stopWatch.ElapsedTicks}
Is Running: {stopWatch.IsRunning}
Frequency: {Stopwatch.Frequency}
Using High Resolution: {Stopwatch.IsHighResolution}");
The Stopwatch class has two static read-only fields: Frequency and IsHighResolution. The former returns the timer frequency denoted as ticks per second, while the latter indicates whether the timer uses a high-resolution performance timer. Therefore, we retrieve their values directly as Stopwatch.Frequency and Stopwatch.IsHighResolution instead of using our stopWatch class instance.
Let’s check the result after executing the program. The timings change on every run:
Elapsed Time: 00:00:00.0003054 Elapsed Milliseconds: 0 Elapsed Ticks: 3054 Is Running: False Frequency: 10000000 Using High Resolution: True
In some cases, we may want to initialize a new Stopwatch instance and restart the process of measuring elapsed time. That’s where we can invoke the StartNew() method:
var stopWatch = Stopwatch.StartNew();
This approach is different from simply initializing a new Stopwatch instance with the default constructor. When we use the StartNew() method, apart from initializing a new instance, we automatically start measuring elapsed time.
What Is the Difference Between Elapsed, ElapsedMilliseconds and ElapsedTicks?
All three read the same measured time, in different units.
Elapsed returns a TimeSpan. It’s the one we want most of the time, because a TimeSpan gives us any unit we like through TotalMilliseconds or TotalSeconds, fractions included.
ElapsedMilliseconds returns a long with whole milliseconds, rounded down. Anything under one millisecond reads as 0, which is fine for a slow database call and useless for a fast loop. Our output above shows exactly that: Elapsed is 00:00:00.0003054, and ElapsedMilliseconds is 0.
ElapsedTicks returns a long too, but it counts ticks of the underlying timer, not TimeSpan ticks. A TimeSpan tick is always 100 nanoseconds. A stopwatch tick lasts one second divided by Stopwatch.Frequency.
On our Windows machine, Frequency is 10000000, so the two tick counts happen to match: 3054 ticks and 0.3054 milliseconds. On Linux, Frequency is one billion, and the same ticks would be nanoseconds.
Microsoft Learn’s ElapsedTicks reference warns about this in a note: “Stopwatch ticks are different from DateTime.Ticks.” When we need a number to store or compare, Elapsed saves us the conversion. Our article on TimeSpan shows how to format and convert the result.
How Do We Measure Elapsed Time With Stopwatch.GetTimestamp?
Since .NET 7, we don’t need a Stopwatch instance or our own tick math to time a block of code. Stopwatch.GetTimestamp() returns the timer’s current tick count as a long, and Stopwatch.GetElapsedTime() turns timestamps into a TimeSpan.
We take a timestamp before the work and pass it to GetElapsedTime(startTimestamp) afterward. It returns the time between that timestamp and the moment of the call. A second overload, GetElapsedTime(startTimestamp, endTimestamp), measures the time between two timestamps we already have.
Why bother? Stopwatch is a class, so new Stopwatch() and StartNew() allocate an object every time. In our probe on .NET 11, StartNew() allocated 40 bytes and the timestamp pair allocated none. In a console app that doesn’t matter, but in code that runs on every request it adds up.
The trade-off is that a timestamp can’t pause or resume. When we need Stop(), Start() or IsRunning, the instance is still the right tool.
Here’s the random array example again, this time without an instance:
public static TimeSpan CreateRandomArrayWithTimestamp(int size)
{
var startTimestamp = Stopwatch.GetTimestamp();
var array = new int[size];
for (int i = 0; i < size; i++)
array[i] = Random.Shared.Next();
return Stopwatch.GetElapsedTime(startTimestamp);
}
GetElapsedTime() also does the tick conversion from the previous section for us. If we pass it exactly Stopwatch.Frequency ticks, we get one second:
Console.WriteLine($"One second in Stopwatch ticks: {Stopwatch.GetElapsedTime(0, Stopwatch.Frequency)}");
var elapsed = StopWatchMethods.CreateRandomArrayWithTimestamp(1000);
Console.WriteLine($"Elapsed with GetTimestamp: {elapsed.TotalMilliseconds} ms");
The first line is always the same, and the second one changes on every run:
One second in Stopwatch ticks: 00:00:01 Elapsed with GetTimestamp: 0.0396 ms
If our code takes a TimeProvider so that tests can fake the clock, TimeProvider has the same GetTimestamp() and GetElapsedTime() pair. We show it in testing time-dependent code with TimeProvider.
Here’s every Stopwatch method, property and field we’ve used so far, in one place:
| Member | Kind | What it does |
|---|---|---|
Stopwatch.StartNew() | static method | Creates a new instance and starts it |
Start() | method | Starts measuring, or resumes from the time already measured |
Stop() | method | Stops measuring and keeps the elapsed time |
Reset() | method | Stops measuring and sets the elapsed time to zero |
Restart() | method | Sets the elapsed time to zero and starts measuring again |
IsRunning | property, bool | true while the stopwatch is measuring |
Elapsed | property, TimeSpan | Total measured time |
ElapsedMilliseconds | property, long | Total measured time in whole milliseconds, rounded down |
ElapsedTicks | property, long | Total measured time in timer ticks (not TimeSpan ticks) |
Stopwatch.Frequency | static field, long | Timer ticks per second |
Stopwatch.IsHighResolution | static field, bool | Whether the timer is a high-resolution performance counter |
Stopwatch.GetTimestamp() | static method | Current timer tick count, no instance needed |
Stopwatch.GetElapsedTime(start) | static method | TimeSpan from a timestamp to now (.NET 7 and later) |
Stopwatch.GetElapsedTime(start, end) | static method | TimeSpan between two timestamps (.NET 7 and later) |
The two GetElapsedTime() rows are the only members in the table that need .NET 7 or later.
Is Stopwatch Accurate Enough for Benchmarking?
For timing one operation in a running application, yes. For comparing two small pieces of code, a single stopwatch reading isn’t enough.
The timer itself is precise. On our machine IsHighResolution is True and Frequency is 10 million ticks per second, so one tick is 100 nanoseconds. The noise comes from everything around the code we measure.
Our own output shows it. The first CreateRandomArray(1000) call took 0.3054 ms. The same work through GetTimestamp(), later in the same run, took 0.0396 ms. The first call was also the first time our program used Random.Shared, and that first use cost extra: when we call Random.Shared.Next() once before measuring, both calls take about the same time. A single reading can’t tell that apart from the work. Microsoft’s own Stopwatch sample throws away its first run for the same reason.
Garbage collections, which pause our code, and other programs on the machine add noise from run to run too. A fair comparison needs warm-up, many repetitions and statistics.
That’s what BenchmarkDotNet does for us, and it’s the tool to reach for when the question is “which one is faster?”
What about subtracting two DateTime.Now values? Microsoft Learn’s DateTime.Now reference answers that one directly: because of its low resolution, the property “is not suitable for use as a benchmarking tool.” The same page names Stopwatch as the better alternative. If you’re curious why DateTime.Now and DateTime.UtcNow behave differently, we compare DateTime.Now and DateTime.UtcNow in a separate article.
Conclusion
In summary, we’ve learned how to use the Stopwatch class in C#. We can leverage the Stopwatch class to reveal inefficiencies in database queries, network operations, and other critical processes, which can be useful when optimizing them.
For a quick measurement, StartNew(), Stop() and Elapsed are all we need. GetTimestamp() with GetElapsedTime() does the same without an object, and when we compare two pieces of code, BenchmarkDotNet takes over.
Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and MSTest 4.5.3.






