Skip to content

Instantly share code, notes, and snippets.

@ig-sinicyn
Created November 7, 2015 20:44
Show Gist options
  • Save ig-sinicyn/95a3dacdd56289dfb978 to your computer and use it in GitHub Desktop.
Save ig-sinicyn/95a3dacdd56289dfb978 to your computer and use it in GitHub Desktop.
using System;
using System.Globalization;
using System.Runtime;
using System.Threading;
namespace ConsoleApplication1
{
internal class Program
{
// IMPORTANT: run release x64 build without debugging (Ctrl-F5 to launch)
// IMPORTANT: add the following lines into app.config to enable the server GC:
/*
<runtime>
<gcServer enabled="true"/>
</runtime>
*/
private static void Main()
{
Console.WindowWidth = 120;
int SingleAllocSize = 64 * 1024; // lower than LOH treshold
int RepeatCount = 8 * 1024; // +512 mb at each step
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // to ignore locale on console output.
Console.WriteLine("GC batch:");
GCSettings.LatencyMode = GCLatencyMode.Batch;
for (int i = 1; i <= 10; i++)
{
AllocMem(SingleAllocSize, i * RepeatCount);
}
Console.WriteLine();
Console.WriteLine("GC low latency:");
GCSettings.LatencyMode = GCLatencyMode.LowLatency;
for (int i = 1; i <= 10; i++)
{
AllocMem(SingleAllocSize, i * RepeatCount);
}
Console.WriteLine("Done");
Console.ReadKey();
}
private static void AllocMem(int allocSize, int allocCount)
{
var data = new byte[allocCount][];
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
var mem = GC.GetTotalMemory(true);
var gc00 = GC.CollectionCount(0);
var gc01 = GC.CollectionCount(1);
var gc02 = GC.CollectionCount(2);
for (int i = 0; i < data.Length; i++)
{
data[i] = new byte[allocSize];
}
long[] genMem = new long[3];
foreach (var item in data)
{
genMem[GC.GetGeneration(item)] += item.Length;
}
var mem2 = GC.GetTotalMemory(false);
var gc10 = GC.CollectionCount(0);
var gc11 = GC.CollectionCount(1);
var gc12 = GC.CollectionCount(2);
GC.KeepAlive(data);
var m0 = genMem[0] / 1024d / 1024;
var m1 = genMem[1] / 1024d / 1024;
var m2 = genMem[2] / 1024d / 1024;
var mTotal = (mem2 - mem) / 1024d / 1024;
var gcDelta0 = gc10 - gc00;
var gcDelta1 = gc11 - gc01;
var gcDelta2 = gc12 - gc02;
Console.WriteLine(
"Allocated, MB: {0,8:N2} \t GC gen 0|1|2, MB: {1,8:N2} | {2,8:N2} | {3,8:N2} \t GC count 0-1-2: {4}-{5}-{6}",
mTotal, m0, m1, m2, gcDelta0, gcDelta1, gcDelta2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment