Skip to content

Instantly share code, notes, and snippets.

@LeeCampbell
Created October 11, 2015 15:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LeeCampbell/ab17000f19c5232ef055 to your computer and use it in GitHub Desktop.
Save LeeCampbell/ab17000f19c5232ef055 to your computer and use it in GitHub Desktop.
Simple LinqPad sample of how to execute a performance test in C#
void Main()
{
var messageCount = 10000;
var sum =0L;
var result = ThroughputTestResult.Capture(messageCount, () => sum = SumOfSquares(messageCount));
Console.WriteLine($"Result: SumOfSquares({messageCount}) = {sum}");
Console.WriteLine(result.ToString());
}
// Define other methods and classes here
public static long SumOfSquares(int max)
{
var sum = 0L;
for (long i = 0; i < max; i++)
sum += i * i;
return sum;
}
public sealed class GcInfo
{
public static GcInfo Current()
{
return new GcInfo(GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2), GC.GetTotalMemory(forceFullCollection: false));
}
public int Gen0 { get; }
public int Gen1 { get; }
public int Gen2 { get; }
public long TotalBytesAllocated { get; }
public GcInfo(int gen0, int gen1, int gen2, long totalBytesAllocated)
{
Gen0 = gen0;
Gen1 = gen1;
Gen2 = gen2;
TotalBytesAllocated = totalBytesAllocated;
}
public GcInfo Delta(GcInfo previous)
{
return new GcInfo(Gen0 - previous.Gen0, Gen1 - previous.Gen1, Gen2 - previous.Gen2, TotalBytesAllocated - previous.TotalBytesAllocated);
}
}
public sealed class ThroughputTestResult
{
public long Messages { get; private set; }
public TimeSpan Elapsed { get; private set; }
public GcInfo GarbageCollections { get; private set; }
public static ThroughputTestResult Capture(long messages, Action action)
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var initial = GcInfo.Current();
var start = Stopwatch.GetTimestamp();
action();
var elapsedTicks = Stopwatch.GetTimestamp() - start;
var gcDelta = GcInfo.Current().Delta(initial);
return new ThroughputTestResult
{
Messages = messages,
Elapsed = TimeSpan.FromTicks(elapsedTicks),
GarbageCollections = gcDelta
};
}
public override string ToString()
{
return $"Messages='{Messages:N0}', Elapsed='{Elapsed}', msg/sec={(Messages / Elapsed.TotalSeconds):N}, GC[0]={GarbageCollections.Gen0},[1]={GarbageCollections.Gen1},[2]={GarbageCollections.Gen2},[BytesAllocated]={GarbageCollections.TotalBytesAllocated:N0}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment