垃圾回收器 —— 获取内存

来源:互联网 发布:内衣取名知乎 编辑:程序博客网 时间:2024/06/07 06:52

GC类包含了一些内存的相关方法,包括GetTatalMemory方法,这个方法返回垃圾回收器(Garbage Collector)分配给你的应用程序的内存数量。由于有些对象并没有被垃圾回收器收集,所以结果可能存在一些偏差。

long available = GC.GetTotalMemory(false);Console.WriteLine(“Before allocations: {0:N0}”, available);int allocSize = 40000000;byte[] bigArray = new byte[allocSize];available = GC.GetTotalMemory(false);Console.WriteLine(“After allocations: {0:N0}”, available);

结果:

Before allocations: 651,064
After allocations: 40,690,080

也可以从操作系统角度查看程序使用了多少内存:

// Process类在System.Diagnostics名字空间中Process proc = Process.GetCurrentProcess();Console.WriteLine("Process Info: "+Environment.NewLine+"Private Memory Size: {0:N0}"+Environment.NewLine +"Virtual Memory Size: {1:N0}" + Environment.NewLine +"Working Set Size: {2:N0}" + Environment.NewLine +"Paged Memory Size: {3:N0}" + Environment.NewLine +"Paged System Memory Size: {4:N0}" + Environment.NewLine +"Non-paged System Memory Size: {5:N0}" + Environment.NewLine,proc.PrivateMemorySize64,proc.VirtualMemorySize64,proc.WorkingSet64,proc.PagedMemorySize64,proc.PagedSystemMemorySize64,proc.NonpagedSystemMemorySize64 );


 


 

原创粉丝点击