日期:2014-05-18  浏览次数:20930 次

怎么测量当前应用程序的内存占用?Process类?PerformanceCounter类?
网上很多答案说用Process或PerformanceCounter,于是我用了一下的代码测试,看看它们测出的数据是不是和Process Explorer测到的一样。

C# code

    class Program
    {
        static Process process = Process.GetCurrentProcess();

        static PerformanceCounter privateBytesCounter = new PerformanceCounter("Process", "Private Bytes", process.ProcessName);
        static PerformanceCounter workingSetCounter = new PerformanceCounter("Process", "Working Set", process.ProcessName);

        static void Main(string[] args)
        {
            GetMeasure();

            Console.WriteLine("按下回车申请大内存");
            Console.ReadLine();
            int[] arr = new int[10000000];
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = i;
            }

            GetMeasure();

            privateBytesCounter.Dispose();
            workingSetCounter.Dispose();
            Console.ReadKey();
        }

        private static void GetMeasure()
        {
            Console.WriteLine("{0,30} {1,20}", "Private bytes", "working set");
            Console.WriteLine("process数据{0,15} {1,20}", process.PrivateMemorySize64 / 1024, process.WorkingSet64 / 1024);
            Console.WriteLine("性能计数器数据{0,12} {1,20}", privateBytesCounter.NextValue() / 1024, workingSetCounter.NextValue() / 1024);
        }

输出如下

  Private bytes working set
process数据 20720 17488
性能计数器数据 21524 15548
按下回车申请大内存

  Private bytes working set
process数据 20720 17488
性能计数器数据 21524 15548

而Process Explorer显示申请大内存后,内存占用为
63724,60856

所以,是我使用Process或PerformanceCounter的方法错了吗,还是它们不能测到真正的内存占用?

------解决方案--------------------
呃。。上次没仔细看,
问题是在GetCurrentProcess方法返回的Process类是不会实时更新的,
要拿最新的值就得再调用一次GetCurrentProcess方法。