Skip to content

Instantly share code, notes, and snippets.

@Restuta
Created March 1, 2012 04:57
Show Gist options
  • Save Restuta/1947397 to your computer and use it in GitHub Desktop.
Save Restuta/1947397 to your computer and use it in GitHub Desktop.
Measure.Performance (Simplifies work with Stopwatch class)
using System;
using System.Collections.Generic;
namespace PerformanceMeasurementMadeEasy
{
public static class Measure
{
private static readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
/// <summary>
/// Will be executed at the end of each peformance measurment, by default writes elapsed ms to Console
/// </summary>
public static Action<long> WhenDone = elapsedTime => Console.WriteLine(elapsedTime + "ms");
public static void Performance(Action codeToMeasure, string prefix = "")
{
stopwatch.Reset();
stopwatch.Start();
codeToMeasure.Invoke();
stopwatch.Stop();
WhenDone.Invoke(stopwatch.ElapsedMilliseconds);
}
}
class Program
{
static void Main(string[] args)
{
//usage example
//make a one-time-setup of an action you would like to perform after perf. measurement
Measure.WhenDone = x => Console.WriteLine("Execution time: {0}ms", x);
//actual sugar
Measure.Performance(() =>
{
for (int i = 0; i < 10000000; i++)
{
var dict = new Dictionary<string, object>();
dict["key1"] = null;
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment