title: Benchmarking small code samples in C#, can this implementation be improved?
body: <p>Quite often on SO I find myself benchmarking small chunks of code to see which implemnetation is fastest. </p>
  
  <p>Quite often I see comments that benchmarking code does not take into account jitting or the garbage collector. </p>
  
  <p>I have the following simple benchmarking function which I have slowly evolved: </p>
  
  <pre><code>  static void Profile(string description, int iterations, Action func) {
          // warm up 
          func();
          // clean up
          GC.Collect();
  
          var watch = new Stopwatch();
          watch.Start();
          for (int i = 0; i &lt; iterations; i++) {
              func();
          }
          watch.Stop();
          Console.Write(description);
          Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
      }
  </code></pre>
  
  <p>Usage: </p>
  
  <pre><code>Profile("a descriptions", how_many_iterations_to_run, () =&gt;
  {
     // ... code being profiled
  });
  </code></pre>
  
  <p>Does this implementation have any flaws? Is it good enough to show that implementaion X is faster than implementation Y over Z iterations? Can you think of any ways you would improve this? </p>
  
  <p><strong>EDIT</strong>
  Its pretty clear that a time based approach (as opposed to iterations), is preferred, does anyone have any implementations where the time checks do not impact performance? </p>