typestar

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

  1. Stopwatch.StartNew starts clean; Stop freezes the reading.
  2. ElapsedMilliseconds answers the usual question.
  3. ElapsedTicks is the fine-grained figure benchmarks want.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Diagnostics & environment, step 13 of 17 in The .NET library.

← Previous Next →