Logo
Color-Of-Code
  Home   All tags   Terms and Conditions

Stopwatch

December 30, 2018

C# Stopwatch

Assembly (reference)

System

Using directive

using System.Diagostics;

Code

var watch = new Stopwatch();
// ...
watch.Start();
// ... execute the first task to be timed
watch.Stop();

watch.Restart(); // reset and starts again (.NET 4.0)
// ... execute the next task to be timed
watch.Stop();

// results
Console.WriteLine("Elapsed: {0}",         watch.Elapsed);
Console.WriteLine("In milliseconds: {0}", watch.ElapsedMilliseconds);
Console.WriteLine("In timer ticks: {0}",  watch.ElapsedTicks);

Note

var watch = new Stopwatch();
watch.Start();

is equivalent to

var watch = Stopwatch.StartNew();