Last active
March 22, 2024 07:52
-
-
Save migajek/47d2969c3ba1345c42e0860755a2b51b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace MemTestPlain | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
GC.Collect(); // so the stats are available | |
var i = 0; | |
while (i++ < 256) | |
{ | |
MemoryUtils.LogMemoryInfo(); | |
Console.WriteLine($"Allocating next 10Mb, i = {i} (total: {i*10}Mb)"); | |
MemoryUtils.AllocateMemory(10); | |
} | |
Console.WriteLine(MemoryUtils.UseBuffers()); | |
} | |
} | |
internal static class MemoryUtils | |
{ | |
private static readonly List<byte[]> _buffers = new(); | |
public static string GetMemInfo() | |
{ | |
var info = GC.GetGCMemoryInfo(); | |
using var proc = System.Diagnostics.Process.GetCurrentProcess(); | |
return $"ENV: {f(info.MemoryLoadBytes)}/{f(info.TotalAvailableMemoryBytes)}. PrivateMemorySize {f(proc.PrivateMemorySize64)}"; | |
string f(long i) => i.HumanReadableSize(); | |
} | |
public static string HumanReadableSize(this long size) | |
{ | |
var sizes = new[] { "B", "KB", "MB", "GB", "TB" }; | |
var order = 0; | |
while (size >= 1024 && order < sizes.Length - 1) | |
{ | |
order++; | |
size /= 1024; | |
} | |
return $"{size:0.##} {sizes[order]}"; | |
} | |
public static void LogMemoryInfo() | |
{ | |
Console.WriteLine(GetMemInfo()); | |
} | |
public static void AllocateMemory(int sizeInMb) | |
{ | |
try | |
{ | |
var buf = new byte[sizeInMb * 1024 * 1024]; | |
Array.Clear(buf, 0, buf.Length); | |
buf[buf.Length / 2] = (byte)sizeInMb; | |
_buffers.Add(buf); | |
} | |
catch (OutOfMemoryException ex) | |
{ | |
Console.WriteLine("Okay, got OutOfMemoryException!"); | |
throw; | |
} | |
} | |
public static int UseBuffers() => _buffers.Sum(b => b[b.Length / 2]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment