Skip to content

Instantly share code, notes, and snippets.

@jfoshee
Last active August 29, 2015 13:57
Show Gist options
  • Save jfoshee/9476613 to your computer and use it in GitHub Desktop.
Save jfoshee/9476613 to your computer and use it in GitHub Desktop.
PerformanceMeter wraps System.Diagnostics.Stopwatch to easily accumulate basic performance measurements.
using System;
using System.Diagnostics;
namespace Unplugged.Visualization
{
public class PerformanceMeter
{
public int Count { get; private set; }
public double Minimum { get; private set; }
public double Maximum { get; private set; }
public double Average { get; private set; }
public PerformanceMeter()
{
Minimum = Double.MaxValue;
Maximum = Double.MinValue;
}
public IDisposable NewMeasurement()
{
return new PerformanceMeasurement(this);
}
public override string ToString()
{
return String.Format("{0:0.00000}s ({1:0.00000}s - {2:0.00000}s",
Average, Minimum, Maximum);
}
internal void AddMeasurement(double seconds)
{
if (seconds < Minimum)
Minimum = seconds;
if (seconds > Maximum)
Maximum = seconds;
if (Count == 0)
Average = seconds;
else
Average = (Average * Count + seconds) / (Count + 1);
Count++;
}
class PerformanceMeasurement : IDisposable
{
private PerformanceMeter _performanceMeter;
private Stopwatch _stopwatch;
public PerformanceMeasurement(PerformanceMeter performanceMeter)
{
_performanceMeter = performanceMeter;
_stopwatch = Stopwatch.StartNew();
}
public void Dispose()
{
_stopwatch.Stop();
double ticksPerSecond = Stopwatch.Frequency;
double s = _stopwatch.ElapsedTicks / ticksPerSecond;
_performanceMeter.AddMeasurement(s);
}
}
}
}
using NUnit.Framework;
using System.Threading;
using Unplugged.Testing;
namespace Unplugged.Visualization.Tests
{
class PerformanceMeterTest : TestBase<PerformanceMeter>
{
[Test]
public void ShouldPopulateTimersForMinMaxAndAverageForOneReading()
{
using (Subject.NewMeasurement())
Thread.Sleep(234);
Assert.That(Subject.Minimum, Is.InRange(0.23, 0.24));
Assert.That(Subject.Maximum, Is.EqualTo(Subject.Minimum));
Assert.That(Subject.Average, Is.EqualTo(Subject.Minimum));
}
[Test]
public void ShouldUpdateMinMaxAndAverageCorrespondingly()
{
using (Subject.NewMeasurement())
Thread.Sleep(200);
using (Subject.NewMeasurement())
Thread.Sleep(100);
using (Subject.NewMeasurement())
Thread.Sleep(500);
using (Subject.NewMeasurement())
Thread.Sleep(300);
Assert.That(Subject.Minimum, Is.InRange(0.1, 0.11));
Assert.That(Subject.Maximum, Is.InRange(0.5, 0.51));
Assert.That(Subject.Average, Is.InRange(0.275, 0.28));
Assert.That(Subject.Count, Is.EqualTo(4));
}
}
}
using NUnit.Framework;
namespace Unplugged.Testing
{
public class TestBase<T> where T : new()
{
protected T Subject;
[SetUp]
public void TestInitialize()
{
Subject = new T();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment