Skip to content

Stopwatch extension methods

Alex Kamsteeg edited this page Aug 8, 2015 · 1 revision

Overview

SwissArmyKnife adds the following extension methods to Stopwatch:

GetElapsedAndRestart()

.NET's Stopwatch is often used for development-time performance measuring. In many cases several different measurements are taken inside a method, with resetting and restarting the stopwatch multiple times:

var sw = Stopwatch.StartNew();

// Time consuming operation #1

sw.Stop();
var elapsed1 = sw.Elapsed;
sw.Restart();

// Time consuming operation #2

sw.Stop();
var elapsed2 = sw.Elapsed;
sw.Restart();

// Time consuming operation #3

sw.Stop();
var elapsed3 = sw.Elapsed;

The GetElapsedAndRestart() extension method makes this a bit less tedious:

var sw = Stopwatch.StartNew();

// Time consuming operation #1

var elapsed1 = sw.GetElapsedAndRestart();

// Time consuming operation #2

var elapsed3 = sw.GetElapsedAndRestart();

// Time consuming operation #3

sw.Stop();
var elapsed3 = sw.Elapsed;