Skip to content

Instantly share code, notes, and snippets.

@adamsitnik
Created December 28, 2016 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamsitnik/7add21f5b1c6f21d5afe186be2403188 to your computer and use it in GitHub Desktop.
Save adamsitnik/7add21f5b1c6f21d5afe186be2403188 to your computer and use it in GitHub Desktop.
memory monitoring
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace TotalMemory
{
public class Program
{
private static readonly Func<long> getAllocatedBytesForCurrentThread = GetAllocatedBytesForCurrentThread();
public static void Main(string[] args)
{
TestMonitoringTotalAllocatedMemorySize();
}
public static void TestMonitoringTotalAllocatedMemorySize()
{
#if CLASSIC
AppDomain.MonitoringIsEnabled = true;
#endif
var temp = new HashSet<string>();
temp.Add("provoke JIT, static ctors etc");
if(temp.Count != 1)
Environment.FailFast("Impossible");
var countersToUse = new [] {1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 100000, 250000, 500000};
foreach (var counter in countersToUse)
{
var hashSetBefore = GetMemory();
var loopCounter = 0;
for (int i = 0; i < counter; i++)
{
var test = new HashSet<string>();
loopCounter += test.Count;
}
var hashSetAfter = GetMemory();
var totalAlloc = hashSetAfter - hashSetBefore;
Console.WriteLine(
"HashSet<string>() = {0,8:N2} bytes (Total = {1,12:N0} bytes, Counter = {2,8:N0}), Current = {3,8:N0} bytes",
(double)totalAlloc / counter, totalAlloc, counter, GC.GetTotalMemory(forceFullCollection: true));
}
}
static long GetMemory()
{
GC.Collect();
#if CLASSIC
return AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize;
#else
return getAllocatedBytesForCurrentThread();
#endif
}
static Func<long> GetAllocatedBytesForCurrentThread()
{
// for some versions of .NET Core this method is internal,
// for some public and for others public and exposed ;)
var method = typeof(GC).GetTypeInfo().GetMethod("GetAllocatedBytesForCurrentThread",
BindingFlags.Public | BindingFlags.Static)
?? typeof(GC).GetTypeInfo().GetMethod("GetAllocatedBytesForCurrentThread",
BindingFlags.NonPublic | BindingFlags.Static);
return () => (long)method.Invoke(null, null);
}
}
}
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": false,
"System.GC.Concurrent": true
}
},
"frameworks": {
"net45": {
"buildOptions": {
"define": [ "CLASSIC" ]
},
"frameworkAssemblies": {
"System.Reflection": "4.0.0.0"
}
},
"netcoreapp1.1": {
"buildOptions": {
"define": [ "CORE" ]
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.1.0"
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment