To find out how long a piece of code takes, use System.Diagnostics.Stopwatch. It reads a high-resolution timer from the operating system, so it is precise to well under a microsecond and, unlike DateTime.Now, it is not affected by clock adjustments.
using System.Diagnostics;
var stopwatch = Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
Thread.Sleep(10);
}
stopwatch.Stop();
Console.WriteLine($"Elapsed: {stopwatch.ElapsedMilliseconds} ms");
Console.WriteLine($"Elapsed: {stopwatch.Elapsed.TotalMilliseconds:F3} ms");
Stopwatch.StartNew() creates and starts the timer in one call. The result is available in three forms:
Elapsedis aTimeSpan, the most convenient for display and arithmetic.ElapsedMillisecondsis alongand drops the fraction, so a 0.9 ms operation reports 0. UseElapsed.TotalMillisecondsfor short operations.ElapsedTickscounts ticks of the underlying timer, notTimeSpanticks. Divide byStopwatch.Frequencyto get seconds. Mixing the two kinds of tick is a common bug.
Do not expect exactly 100 ms from the example. Thread.Sleep(10) waits *at least* 10 ms, and on Windows the default timer resolution is about 15.6 ms, so the loop often takes 150 ms or more. Measuring is how you find out things like that.
Without allocating a Stopwatch (.NET 7 and later)
For timing in hot paths, such as middleware that logs the duration of every request, you can skip the object and work with raw timestamps:
using System.Diagnostics;
long start = Stopwatch.GetTimestamp();
await Task.Delay(250);
TimeSpan elapsed = Stopwatch.GetElapsedTime(start);
Console.WriteLine($"Took {elapsed.TotalMilliseconds:F1} ms");
GetTimestamp returns a long, so nothing is allocated. Both styles work across await, because they compare two readings of the clock rather than measuring a thread.
A small helper keeps call sites short:
static TimeSpan Measure(Action action)
{
long start = Stopwatch.GetTimestamp();
action();
return Stopwatch.GetElapsedTime(start);
}
TimeSpan t = Measure(() => File.ReadAllText("data.json"));
Reusing a Stopwatch
Stop() pauses the timer and Start() continues it, adding to the elapsed time. That is handy for timing only part of each loop iteration. Reset() stops it and sets the elapsed time to zero; Restart() does the same and starts it again in one call, which is what you usually want between measurements.
A Stopwatch instance is not thread-safe. Give each thread or each concurrent request its own, or use the timestamp approach above.
Why one measurement is not a benchmark
A single Stopwatch reading is fine for “this import takes about four seconds”. It is misleading for comparing two implementations of a method that runs in microseconds:
- JIT compilation. The first call to a method includes compiling it. Run it once before you start measuring.
- Tiered compilation. .NET first compiles quickly with few optimizations and recompiles hot methods later, so early iterations are slower than steady state.
- Debug builds. A Debug build, or a Release build with the debugger attached, disables many optimizations. Measure Release builds started without debugging (
dotnet run -c Release). - Noise. Garbage collections, other processes and CPU frequency scaling all shift single readings. Run many iterations and look at the average and the spread.
For micro-benchmarks, use BenchmarkDotNet. It handles warm-up, runs enough iterations to be statistically meaningful, and reports memory allocations:
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<ConcatBenchmarks>();
[MemoryDiagnoser]
public class ConcatBenchmarks
{
private readonly string[] _parts =
Enumerable.Range(0, 100).Select(i => i.ToString()).ToArray();
[Benchmark(Baseline = true)]
public string PlusOperator()
{
string result = "";
foreach (string part in _parts)
{
result += part;
}
return result;
}
[Benchmark]
public string Builder()
{
var sb = new StringBuilder();
foreach (string part in _parts)
{
sb.Append(part);
}
return sb.ToString();
}
}
Add the BenchmarkDotNet NuGet package and run the project with dotnet run -c Release. BenchmarkDotNet refuses to run a Debug build, for the reasons above.
For production code, prefer metrics over ad-hoc timing: System.Diagnostics.Metrics histograms, or the request duration that ASP.NET Core and OpenTelemetry already record, give you percentiles over time instead of one number in a log line.