Stopwatch in C#
Measure elapsed time with the clock made for it.
using System.Diagnostics;
var watch = Stopwatch.StartNew();
var total = 0L;
for (var i = 0; i < 1_000_000; i++)
{
total += i;
}
watch.Stop();
Console.WriteLine($"sum {total}");
Console.WriteLine($"took {watch.ElapsedMilliseconds}ms");
Console.WriteLine($"ticks are finer: {watch.ElapsedTicks}");
How it works
Stopwatch.StartNewstarts clean;Stopfreezes the reading.ElapsedMillisecondsanswers the usual question.ElapsedTicksis the fine-grained figure benchmarks want.
Keywords and builtins used here
forusingvar
The run, in numbers
- Lines
- 13
- Characters to type
- 297
- Tokens
- 65
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 41 seconds.
Step 1 of 3 in Diagnostics & environment, step 13 of 17 in The .NET library.