Skip to content

Instantly share code, notes, and snippets.

@sihugh
Created October 12, 2012 14:55
Show Gist options
  • Save sihugh/3879599 to your computer and use it in GitHub Desktop.
Save sihugh/3879599 to your computer and use it in GitHub Desktop.
Code to profile a method - allows for easy comparison between two similar approaches
using System;
using System.Diagnostics;
namespace Benchmark
{
/// <summary>
/// This code has been adapted from the question at http://stackoverflow.com/questions/1047218/benchmarking-small-code-samples-in-c-can-this-implementation-be-improved
/// </summary>
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Finished");
Console.ReadLine();
}
static void Profile(string description, int iterations, Action action)
{
// clean up
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
// warm up
action();
var watch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
action();
}
watch.Stop();
Console.Write(description);
Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment