C#中的内存压力测试

Cha*_*ila 5 c# memory-management stress-testing

我想创建一个工具来模拟内存限制,以便对内存压力测试其他应用程序.在完成一些谷歌搜索后,我想出了以下代码,但在运行时,任务管理器或资源监视器没有显示内存使用情况的任何差异.只是一条扁线.

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace Win32Tute
{
    unsafe class Program
    {
        // Heap API flags
        const int HEAP_ZERO_MEMORY = 0x00000008;
        // Heap API functions
        [DllImport("kernel32")]
        static extern int GetProcessHeap();
        [DllImport("kernel32")]
        static extern void* HeapAlloc(int hHeap, int flags, int size);
        [DllImport("kernel32")]
        static extern bool HeapFree(int hHeap, int flags, void* block);

        private static int ph = GetProcessHeap();

        public static void* Alloc(int size)
        {
            void* result = HeapAlloc(ph, HEAP_ZERO_MEMORY, size);
            if(result == null) throw new OutOfMemoryException("Couldn't execute HeapAlloc");
            return result;
        }

        public static void Free(void* block)
        {
            if(!HeapFree(ph, 0, block)) throw new InvalidOperationException("Couldn't free memory");
        }

        public static void Main(string[] args)
        {
            int blockSize = 1024*1024; //1mb
            byte*[] handles = new byte*[1024];
            Console.WriteLine("Memory before : " + (Process.GetCurrentProcess().PrivateMemorySize64/1024)/1024); // get value in Megabytes
            try
            {
                for(int i=0; i<1024; i++)
                {
                   handles[i] = (byte*)Alloc(blockSize);

                }
            }
            finally
            {
                Console.WriteLine("Memory after  : " + (Process.GetCurrentProcess().PrivateMemorySize64 / 1024)/1024);
                Console.WriteLine("Finished allocating 1024MB memory....Press Enter to free up.");
                Console.ReadLine();
            }

            try
            {
                for(int i=0; i<1024; i++)
                {
                    Free(handles[i]);
                }
            }
            finally
            {
                Console.WriteLine("Memory at the end : " + (Process.GetCurrentProcess().PrivateMemorySize64 / 1024)/1024);
                Console.WriteLine("All allocated memory freed. Press Enter to quit..");
                Console.ReadLine();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jim*_*hel 5

这种事情几乎总是一个坏主意。如果您成功地创建了一个占用内存的程序,您可能会发现这样做并不会阻止其他程序的响应。虚拟内存管理器将竭尽全力保持其他程序的运行。例如,它会将内存占用的数据分页到磁盘,以便将工作程序的数据保存在它所属的内存中。如果你修改你的内存猪,使它锁定内存中的页面(即不让页面被换出),那么计算机将开始抖动。

你最好在你正在测试的程序中编写诊断代码,让你调用SetProcessWorkingSetSizeEx来测试程序在不同的内存条件下如何响应。如果您不能修改您正在测试的程序,您可以编写一个程序来获取测试程序的句柄并调用SetProcessWorkingSetSizeEx,传递该句柄。