Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping StopWatch timing with a delegate or lambda?

I'm writing code like this, doing a little quick and dirty timing:

var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000; i++) {     b = DoStuff(s); } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); 

Surely there's a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the DoStuff(s) with DoSomethingElse(s)?

I know it can be done as a Delegate but I'm wondering about the lambda way.

like image 565
Jeff Atwood Avatar asked Oct 24 '08 08:10

Jeff Atwood


2 Answers

How about extending the Stopwatch class?

public static class StopwatchExtensions {     public static long Time(this Stopwatch sw, Action action, int iterations)     {         sw.Reset();         sw.Start();          for (int i = 0; i < iterations; i++)         {             action();         }         sw.Stop();          return sw.ElapsedMilliseconds;     } } 

Then call it like this:

var s = new Stopwatch(); Console.WriteLine(s.Time(() => DoStuff(), 1000)); 

You could add another overload which omits the "iterations" parameter and calls this version with some default value (like 1000).

like image 199
Matt Hamilton Avatar answered Nov 15 '22 14:11

Matt Hamilton


Here's what I've been using:

public class DisposableStopwatch: IDisposable {     private readonly Stopwatch sw;     private readonly Action<TimeSpan> f;      public DisposableStopwatch(Action<TimeSpan> f) {         this.f = f;         sw = Stopwatch.StartNew();     }      public void Dispose() {         sw.Stop();         f(sw.Elapsed);     } } 

Usage:

using (new DisposableStopwatch(t => Console.WriteLine("{0} elapsed", t))) {   // do stuff that I want to measure } 
like image 41
Mauricio Scheffer Avatar answered Nov 15 '22 13:11

Mauricio Scheffer