ZetCode

C# Stopwatch

last modified November 15, 2026

This article shows how to measure elapsed time in C# with the Stopwatch class.

Stopwatch from the System.Diagnostics namespace measures elapsed time with the most precise timer the operating system offers. Unlike DateTime.Now, it is not affected by changes of the system clock, so it is the right tool for timing code, logging the duration of operations, and simple performance comparisons.

Member Description
StartNew Creates and starts a new stopwatch.
Start, Stop Start or resume, and pause the measurement.
Restart, Reset Set the elapsed time to zero, and start or stop.
Elapsed Elapsed time as a TimeSpan.
ElapsedMilliseconds, ElapsedTicks Elapsed time in whole milliseconds or in timer ticks.
IsRunning Whether the stopwatch is running.
GetTimestamp, GetElapsedTime Static, allocation-free timing.
Frequency, IsHighResolution Properties of the underlying timer.

The times in the outputs below were measured on one machine and differ from run to run.

C# Stopwatch basic example

The basic pattern is to start the stopwatch, run the code, stop it, and read the elapsed time.

Program.cs
using System.Diagnostics;

var sw = Stopwatch.StartNew();

long sum = 0;

for (int i = 0; i < 100_000_000; i++)
{
    sum += i % 7;
}

sw.Stop();

Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Elapsed: {sw.Elapsed}");
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalMilliseconds:F3} ms");

We measure a loop that runs a hundred million times.

var sw = Stopwatch.StartNew();

StartNew creates a stopwatch and starts it. It is a shortcut for calling the constructor and then Start.

Console.WriteLine($"Elapsed: {sw.Elapsed}");
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");
Console.WriteLine($"Elapsed: {sw.Elapsed.TotalMilliseconds:F3} ms");

Elapsed returns a TimeSpan. ElapsedMilliseconds is a long with whole milliseconds; the fraction is truncated. For sub-millisecond precision, use Elapsed.TotalMilliseconds, which is a double.

$ dotnet run
Sum: 299999995
Elapsed: 00:00:00.1558831
Elapsed: 155 ms
Elapsed: 155.883 ms

C# Stopwatch ticks and frequency

The stopwatch counts ticks of a hardware timer. The word tick has two different meanings here, which is a common source of bugs.

Program.cs
using System.Diagnostics;

Console.WriteLine($"High resolution: {Stopwatch.IsHighResolution}");
Console.WriteLine($"Frequency: {Stopwatch.Frequency:N0} ticks/s");
Console.WriteLine($"Tick length: {1_000_000_000.0 / Stopwatch.Frequency} ns");

var sw = Stopwatch.StartNew();
Thread.Sleep(50);
sw.Stop();

Console.WriteLine($"ElapsedTicks: {sw.ElapsedTicks:N0}");
Console.WriteLine($"Elapsed.Ticks: {sw.Elapsed.Ticks:N0}");
Console.WriteLine($"TimeSpan.TicksPerSecond: {TimeSpan.TicksPerSecond:N0}");

double ms = sw.ElapsedTicks * 1000.0 / Stopwatch.Frequency;
Console.WriteLine($"{ms:F1} ms");

We print the properties of the timer and compare two kinds of ticks.

Console.WriteLine($"Frequency: {Stopwatch.Frequency:N0} ticks/s");

Frequency is the number of timer ticks per second. On Linux, it is one billion, so a tick is one nanosecond; on Windows, it is typically ten million. IsHighResolution tells if a high-resolution performance counter is available.

Console.WriteLine($"ElapsedTicks: {sw.ElapsedTicks:N0}");
Console.WriteLine($"Elapsed.Ticks: {sw.Elapsed.Ticks:N0}");

ElapsedTicks is in timer ticks. Elapsed.Ticks is in TimeSpan ticks, which are always 100 nanoseconds. On this machine, the two numbers differ by a factor of 100.

double ms = sw.ElapsedTicks * 1000.0 / Stopwatch.Frequency;

To convert ElapsedTicks to time units, divide by Frequency. Passing ElapsedTicks to TimeSpan.FromTicks gives a wrong result on systems where the frequency is not ten million. Usually it is simpler to use Elapsed directly.

$ dotnet run
High resolution: True
Frequency: 1,000,000,000 ticks/s
Tick length: 1 ns
ElapsedTicks: 50,262,907
Elapsed.Ticks: 502,629
TimeSpan.TicksPerSecond: 10,000,000
50.3 ms

C# Stopwatch Start, Stop, Restart, and Reset

A stopped stopwatch can be started again; the elapsed time then continues from where it stopped.

Program.cs
using System.Diagnostics;

var sw = new Stopwatch();
Console.WriteLine($"Running: {sw.IsRunning}, elapsed: {sw.ElapsedMilliseconds}");

sw.Start();
Thread.Sleep(100);
sw.Stop();

Thread.Sleep(200);

sw.Start();
Thread.Sleep(100);
sw.Stop();

Console.WriteLine($"Running: {sw.IsRunning}, elapsed: ~{Round(sw.ElapsedMilliseconds)} ms");

sw.Restart();
Thread.Sleep(50);
Console.WriteLine($"Running: {sw.IsRunning}, elapsed: ~{Round(sw.ElapsedMilliseconds)} ms");

sw.Reset();
Console.WriteLine($"Running: {sw.IsRunning}, elapsed: {sw.ElapsedMilliseconds}");

static long Round(long ms) => (ms + 5) / 10 * 10;

We measure two intervals with a pause between them.

sw.Start();
Thread.Sleep(100);
sw.Stop();

Thread.Sleep(200);

The 200 ms pause happens while the stopwatch is stopped, so it is not counted. The total of the two measured intervals is about 200 ms. We round the printed values to tens of milliseconds, since Thread.Sleep is not exact.

sw.Restart();

Restart sets the elapsed time to zero and starts the stopwatch again.

sw.Reset();

Reset sets the elapsed time to zero and stops the stopwatch.

$ dotnet run
Running: False, elapsed: 0
Running: False, elapsed: ~200 ms
Running: True, elapsed: ~50 ms
Running: False, elapsed: 0

C# Stopwatch lap times

With two stopwatches, we can measure both the individual steps and the total time of an operation.

Program.cs
using System.Diagnostics;

var total = Stopwatch.StartNew();
var lap = Stopwatch.StartNew();

string[] steps = ["load", "parse", "save"];
int[] delays = [120, 60, 30];

for (int i = 0; i < steps.Length; i++)
{
    Thread.Sleep(delays[i]);
    Console.WriteLine($"{steps[i],-6} {lap.ElapsedMilliseconds,4} ms");
    lap.Restart();
}

Console.WriteLine($"{"total",-6} {total.ElapsedMilliseconds,4} ms");

We simulate three steps with different durations.

Console.WriteLine($"{steps[i],-6} {lap.ElapsedMilliseconds,4} ms");
lap.Restart();

After each step, we print the time of the lap and restart the lap stopwatch. The total stopwatch keeps running. The total is larger than the sum of the laps, because the time spent printing, between reading the lap time and restarting the lap stopwatch, is counted only by the total stopwatch.

$ dotnet run
load    125 ms
parse    60 ms
save     30 ms
total   233 ms

C# Stopwatch GetTimestamp and GetElapsedTime

Stopwatch is a class, so each instance is an object on the heap. The static GetTimestamp method returns the current value of the timer as a long, and GetElapsedTime (.NET 7) converts the difference of timestamps into a TimeSpan. This avoids allocations, which matters in frequently called code such as request logging.

Program.cs
using System.Diagnostics;

long start = Stopwatch.GetTimestamp();

await Task.Delay(150);

TimeSpan elapsed = Stopwatch.GetElapsedTime(start);
Console.WriteLine($"Task.Delay(150): {elapsed.TotalMilliseconds:F1} ms");

long t1 = Stopwatch.GetTimestamp();
var data = Enumerable.Range(1, 10_000_000).Where(n => n % 2 == 0).Select(n => (long)n * n).ToArray();
long t2 = Stopwatch.GetTimestamp();

Console.WriteLine($"LINQ: {data.Length:N0} items in {Stopwatch.GetElapsedTime(t1, t2).TotalMilliseconds:F1} ms");

We time an asynchronous delay and a LINQ query.

long start = Stopwatch.GetTimestamp();

await Task.Delay(150);

TimeSpan elapsed = Stopwatch.GetElapsedTime(start);

With one argument, GetElapsedTime returns the time from the timestamp until now. The measured time is a few milliseconds longer than requested; Task.Delay guarantees a minimum, not an exact delay.

Console.WriteLine($"LINQ: {data.Length:N0} items in {Stopwatch.GetElapsedTime(t1, t2).TotalMilliseconds:F1} ms");

The overload with two timestamps returns the time between them.

$ dotnet run
Task.Delay(150): 153.8 ms
LINQ: 5,000,000 items in 70.6 ms

The first run is slower

When a method runs for the first time, the JIT compiler translates it to machine code. The runtime later recompiles frequently used methods with more optimizations (tiered compilation). A single measurement of a short operation therefore says little.

Program.cs
using System.Diagnostics;

int[] data = Enumerable.Range(0, 1000).Reverse().ToArray();

for (int run = 1; run <= 5; run++)
{
    int[] copy = (int[])data.Clone();

    long start = Stopwatch.GetTimestamp();
    Array.Sort(copy);
    var elapsed = Stopwatch.GetElapsedTime(start);

    Console.WriteLine($"run {run}: {elapsed.TotalMicroseconds,8:F1} µs");
}

We sort the same 1,000 numbers five times and time each run.

int[] copy = (int[])data.Clone();

Each run sorts a fresh copy, so every run does the same work.

Console.WriteLine($"run {run}: {elapsed.TotalMicroseconds,8:F1} µs");

The first run takes more than twenty times longer than the last ones. It includes the JIT compilation of the sorting code. To measure reliably, make a warm-up run first and repeat the measurement several times.

$ dotnet run
run 1:    167.0 µs
run 2:     20.5 µs
run 3:      7.7 µs
run 4:      6.8 µs
run 5:      7.0 µs

C# Stopwatch comparing algorithms

With warm-up and repetition, Stopwatch is good enough for rough comparisons of algorithms.

Program.cs
using System.Diagnostics;

var rnd = new Random(1);
int[] data = Enumerable.Range(0, 30_000).Select(_ => rnd.Next(1, 100_000)).ToArray();

Measure("selection sort", data, SelectionSort);
Measure("bubble sort", data, BubbleSort);
Measure("Array.Sort", data, Array.Sort);

static void Measure(string name, int[] source, Action<int[]> sort)
{
    var times = new List<double>();

    for (int i = 0; i < 4; i++)
    {
        int[] copy = (int[])source.Clone();
        var sw = Stopwatch.StartNew();
        sort(copy);
        sw.Stop();

        if (i > 0)
        {
            times.Add(sw.Elapsed.TotalMilliseconds);
        }
    }

    Console.WriteLine($"{name,-15} min {times.Min(),8:F2} ms   avg {times.Average(),8:F2} ms");
}

static void SelectionSort(int[] a)
{
    for (int i = 0; i < a.Length - 1; i++)
    {
        int min = i;

        for (int j = i + 1; j < a.Length; j++)
        {
            if (a[j] < a[min])
            {
                min = j;
            }
        }

        (a[i], a[min]) = (a[min], a[i]);
    }
}

static void BubbleSort(int[] a)
{
    for (int i = 0; i < a.Length - 1; i++)
    {
        for (int j = 0; j < a.Length - i - 1; j++)
        {
            if (a[j] > a[j + 1])
            {
                (a[j], a[j + 1]) = (a[j + 1], a[j]);
            }
        }
    }
}

We compare the selection sort, the bubble sort, and Array.Sort on 30,000 random integers.

if (i > 0)
{
    times.Add(sw.Elapsed.TotalMilliseconds);
}

Each algorithm runs four times on copies of the same data. The first run is a warm-up and is not recorded; we print the minimum and the average of the other three.

var rnd = new Random(1);

The seeded generator creates the same data on every run of the program.

Performance must be measured in the Release configuration; Debug builds disable many optimizations. Both simple sorts are O(n2), but the selection sort does far fewer swaps than the bubble sort. The O(n log n) Array.Sort is hundreds of times faster than both. For precise benchmarks with statistics, use BenchmarkDotNet.

$ dotnet run -c Release
selection sort  min   230.29 ms   avg   231.69 ms
bubble sort     min  1087.46 ms   avg  1098.90 ms
Array.Sort      min     1.35 ms   avg     1.36 ms

C# timing scope

A small helper type that implements IDisposable can time a block of code with the using statement.

Program.cs
using System.Diagnostics;
using System.Text;

using (new Timing("+= concatenation"))
{
    var text = string.Empty;

    for (int i = 0; i < 50_000; i++)
    {
        text += "abc";
    }
}

using (new Timing("StringBuilder"))
{
    var sb = new StringBuilder();

    for (int i = 0; i < 50_000; i++)
    {
        sb.Append("abc");
    }

    var text = sb.ToString();
}

sealed class Timing(string name) : IDisposable
{
    private readonly long start = Stopwatch.GetTimestamp();

    public void Dispose()
    {
        var elapsed = Stopwatch.GetElapsedTime(start);
        Console.WriteLine($"{name}: {elapsed.TotalMilliseconds:F2} ms");
    }
}

We compare string concatenation with StringBuilder.

sealed class Timing(string name) : IDisposable
{
    private readonly long start = Stopwatch.GetTimestamp();

The timestamp is taken when the object is created at the start of the using block.

public void Dispose()
{
    var elapsed = Stopwatch.GetElapsedTime(start);
    Console.WriteLine($"{name}: {elapsed.TotalMilliseconds:F2} ms");
}

Dispose is called when the block ends, even if an exception is thrown, and prints the elapsed time. Building a string with += copies the whole string in each iteration, which is why it is more than a thousand times slower; see the StringBuilder article.

$ dotnet run
+= concatenation: 485.50 ms
StringBuilder: 0.33 ms

Source

Stopwatch class - .NET API

In this article we have measured elapsed time with the C# Stopwatch class. See also the benchmark, TimeSpan, and PeriodicTimer tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.