一个完整的吃内存程序

原创 2006年05月24日 21:53:00
一个完整的吃内存程序
作者:苏显斌
日期:2006年5月24日
这个程序是本人在公司测试自己编写的安装程序其间编写的一个小程序,主要目的是用来测试本机在不同剩余内存的情况下,安装程序执行的情况,现在把这个工具放上来给大家共享,希望有用得到的,同时也希望各位在阅读代码的过程中,发现有设计、编码等问题,不吝给予指出。
 
一、             界面设计
 
二、             界面部分的代码
/*
 * 名称:吃掉内存程序
 * 说明:用于吃掉物理内存的大小,以便可以进行软件的压力测试。
 * 作者:苏显斌
 * 创建日期:2006-03-02
 * 修改补充:
*/
 
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
 
namespace SetupMemoryTest
{
     ///<summary>
     /// Form1 的摘要说明。
     ///</summary>
     public class Form1 : System.Windows.Forms.Form
     {
         public delegate void ReleaseButtonHandler(bool isEnable);
         public delegate void ShowErrorMessageHandler(Exception ex);
 
         private bool isCancel = false;
         private ReleaseButtonHandler releaseButton;
         private ShowErrorMessageHandler showErrorMessage;
 
         private System.Windows.Forms.TextBox eatMemorySize;
         private System.Windows.Forms.Button excute;
         private System.Windows.Forms.Label label1;
         private System.Windows.Forms.Label label2;
         private System.Windows.Forms.Label availableMemory;
         private System.Windows.Forms.Label totalMemory;
         private System.Windows.Forms.Label label4;
         private System.Windows.Forms.Timer timer1;
         private System.Windows.Forms.Label label3;
         private System.Windows.Forms.Button releaseMemory;
         private System.Windows.Forms.StatusBar statusBar1;
         private System.Windows.Forms.StatusBarPanel statusBarPanel1;
         private System.ComponentModel.IContainer components;
 
         public Form1()
         {
              //
              // Windows 窗体设计器支持所必需的
              //
              InitializeComponent();
 
              releaseButton = new ReleaseButtonHandler(this.SetReleaseButton);
              showErrorMessage = new ShowErrorMessageHandler(this.ShowErrorMessage);
         }
 
         ///<summary>
         ///清理所有正在使用的资源。
         ///</summary>
         protected override void Dispose( bool disposing )
         {
              if( disposing )
              {
                   if (components != null)
                   {
                       components.Dispose();
                   }
              }
              base.Dispose( disposing );
         }
 
         #region Windows 窗体设计器生成的代码
         ///<summary>
         ///设计器支持所需的方法 - 不要使用代码编辑器修改
         ///此方法的内容。
         ///</summary>
         private void InitializeComponent()
         {
              this.components = new System.ComponentModel.Container();
              this.eatMemorySize = new System.Windows.Forms.TextBox();
              this.excute = new System.Windows.Forms.Button();
              this.label1 = new System.Windows.Forms.Label();
              this.label2 = new System.Windows.Forms.Label();
              this.availableMemory = new System.Windows.Forms.Label();
              this.totalMemory = new System.Windows.Forms.Label();
              this.label4 = new System.Windows.Forms.Label();
              this.timer1 = new System.Windows.Forms.Timer(this.components);
              this.label3 = new System.Windows.Forms.Label();
              this.releaseMemory = new System.Windows.Forms.Button();
              this.statusBar1 = new System.Windows.Forms.StatusBar();
              this.statusBarPanel1 = new System.Windows.Forms.StatusBarPanel();
              ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).BeginInit();
              this.SuspendLayout();
              //
              // eatMemorySize
              //
              this.eatMemorySize.Location = new System.Drawing.Point(112, 16);
              this.eatMemorySize.Name = "eatMemorySize";
              this.eatMemorySize.Size = new System.Drawing.Size(104, 21);
              this.eatMemorySize.TabIndex = 0;
              this.eatMemorySize.Text = "";
              this.eatMemorySize.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.eatMemorySize_KeyPress);
              //
              // excute
              //
              this.excute.Location = new System.Drawing.Point(256, 16);
              this.excute.Name = "excute";
              this.excute.Size = new System.Drawing.Size(56, 24);
              this.excute.TabIndex = 1;
              this.excute.Text = "执行";
              this.excute.Click += new System.EventHandler(this.excute_Click);
              //
              // label1
              //
              this.label1.Location = new System.Drawing.Point(32, 24);
              this.label1.Name = "label1";
              this.label1.Size = new System.Drawing.Size(72, 16);
              this.label1.TabIndex = 2;
              this.label1.Text = "吃掉内存:";
              this.label1.TextAlign = System.Drawing.ContentAlignment.TopRight;
              //
              // label2
              //
              this.label2.Location = new System.Drawing.Point(48, 88);
              this.label2.Name = "label2";
              this.label2.Size = new System.Drawing.Size(64, 16);
              this.label2.TabIndex = 3;
              this.label2.Text = "可用内存:";
              this.label2.TextAlign = System.Drawing.ContentAlignment.TopRight;
              //
              // availableMemory
              //
              this.availableMemory.Location = new System.Drawing.Point(112, 88);
              this.availableMemory.Name = "availableMemory";
              this.availableMemory.Size = new System.Drawing.Size(144, 16);
              this.availableMemory.TabIndex = 4;
              //
              // totalMemory
              //
              this.totalMemory.Location = new System.Drawing.Point(112, 64);
              this.totalMemory.Name = "totalMemory";
              this.totalMemory.Size = new System.Drawing.Size(144, 16);
              this.totalMemory.TabIndex = 6;
              //
              // label4
              //
              this.label4.Location = new System.Drawing.Point(48, 64);
              this.label4.Name = "label4";
              this.label4.Size = new System.Drawing.Size(64, 16);
              this.label4.TabIndex = 5;
              this.label4.Text = "总内存:";
              this.label4.TextAlign = System.Drawing.ContentAlignment.TopRight;
              //
              // timer1
              //
              this.timer1.Enabled = true;
              this.timer1.Interval = 1000;
              this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
              //
              // label3
              //
              this.label3.Location = new System.Drawing.Point(224, 24);
              this.label3.Name = "label3";
              this.label3.Size = new System.Drawing.Size(24, 16);
              this.label3.TabIndex = 7;
              this.label3.Text = "MB";
              //
              // releaseMemory
              //
              this.releaseMemory.Location = new System.Drawing.Point(328, 16);
              this.releaseMemory.Name = "releaseMemory";
              this.releaseMemory.Size = new System.Drawing.Size(48, 24);
              this.releaseMemory.TabIndex = 8;
              this.releaseMemory.Text = "释放";
              this.releaseMemory.Click += new System.EventHandler(this.releaseMemory_Click);
              //
              // statusBar1
              //
              this.statusBar1.Location = new System.Drawing.Point(0, 117);
              this.statusBar1.Name = "statusBar1";
              this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
                                                                                                        this.statusBarPanel1});
              this.statusBar1.RightToLeft = System.Windows.Forms.RightToLeft.No;
              this.statusBar1.ShowPanels = true;
              this.statusBar1.Size = new System.Drawing.Size(400, 24);
              this.statusBar1.SizingGrip = false;
              this.statusBar1.TabIndex = 17;
              //
              // statusBarPanel1
              //
              this.statusBarPanel1.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
              this.statusBarPanel1.Text = "苏显斌 2006.03.03";
              this.statusBarPanel1.Width = 5000;
              //
              // Form1
              //
              this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
              this.ClientSize = new System.Drawing.Size(400, 141);
              this.Controls.Add(this.statusBar1);
              this.Controls.Add(this.releaseMemory);
              this.Controls.Add(this.label3);
              this.Controls.Add(this.totalMemory);
              this.Controls.Add(this.label4);
              this.Controls.Add(this.availableMemory);
              this.Controls.Add(this.label2);
              this.Controls.Add(this.label1);
              this.Controls.Add(this.excute);
              this.Controls.Add(this.eatMemorySize);
              this.Name = "Form1";
              this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
              this.Text = "吃掉内存工具";
              this.Load += new System.EventHandler(this.Form1_Load);
              ((System.ComponentModel.ISupportInitialize)(this.statusBarPanel1)).EndInit();
              this.ResumeLayout(false);
 
         }
         #endregion
 
         ///<summary>
         ///应用程序的主入口点。
         ///</summary>
         [STAThread]
         static void Main()
         {
              Application.Run(new Form1());
         }
 
         private void excute_Click(object sender, System.EventArgs e)
         {
              if (this.eatMemorySize.Text == string.Empty) return;
 
              try
              {
                   if (long.Parse(this.eatMemorySize.Text) <= 0) return;
              }
              catch (System.FormatException)
              {
                   MessageBox.Show("请输入合法整型数值!");
                   return;
              }
 
              this.excute.Enabled = false;
 
              GC.Collect();
 
              long size = long.Parse(this.eatMemorySize.Text.Trim());
              ThreadPool.QueueUserWorkItem(new WaitCallback(this.EatMemory), size);
         }
 
         private void timer1_Tick(object sender, System.EventArgs e)
         {
              this.totalMemory.Text = int.Parse(((int)(MemoryHelper.GetTotalPhysicalMemory() /1024 / 1024)).ToString()).ToString() + " MB";
              this.availableMemory.Text = int.Parse(((int)(MemoryHelper.GetAvailablePhysicalMemory() / 1024 / 1024)).ToString()).ToString() + " MB";
         }
 
         private void EatMemory(object size)
         {
              this.isCancel = false;
              long eatMem = (long) size * 1024 * 1024;
 
              byte []memory = null;
              try
              {
                   memory = new byte[eatMem];
              }
              catch (System.Exception ex)
              {
                   this.BeginInvoke(this.showErrorMessage, new object[] {ex});
                   return;
              }
 
              for (long i = 0; i < eatMem && !this.isCancel; i++) memory[i] = (byte) '1';
 
              while (this.isCancel == false) Thread.Sleep(100);
         }
 
         private void releaseMemory_Click(object sender, System.EventArgs e)
         {
              ((Control) sender).Enabled = false;
              this.isCancel = true;
 
              Thread.Sleep(500);
              Thread thread = new Thread(new ThreadStart(ClearMemory));
              thread.Start();
         }
 
         private void ClearMemory()
         {
              GC.Collect();
 
              this.Invoke(this.releaseButton, new object []{true});
         }
 
         private void Form1_Load(object sender, System.EventArgs e)
         {
             
         }
 
         private void SetReleaseButton(bool isEnable)
         {
              this.releaseMemory.Enabled = isEnable;
              this.excute.Enabled = true;
         }
 
         private void ShowErrorMessage(Exception ex)
         {
              MessageBox.Show(ex.Message);
         }
 
         private void eatMemorySize_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
         {
              if (e.KeyChar != 8 && (e.KeyChar < (char) '0' || e.KeyChar > (char) '9')) e.Handled = true;
         }
     }
}
 
三、             MemoryHelper类设计
/*
 * 名称:MemoryHelper 类
 * 说明:获取系统内存信息的类。
 * 作者:苏显斌
 * 创建日期:2006-03-02
 * 修改补充:
*/
 
using System;
using System.Runtime.InteropServices;
 
namespace SetupMemoryTest
{
     ///<summary>
     ///获取系统内存信息的类。
     ///</summary>
     public sealed class MemoryHelper
     {
         [StructLayout(LayoutKind.Sequential)]
              public struct MemoryStruct
         {
              public uint dwLength;       // Size of the MEMORYSTATUS data structure, in bytes. You do not need to set this member before calling the GlobalMemoryStatus function; the function sets it.
              public uint dwMemoryLoad;   // Approximate percentage of total physical memory that is in use.
              public uint dwTotalPhys;         // Total size of physical memory, in bytes.
              public uint dwAvailPhys;         // Size of physical memory available, in bytes.
              public uint dwTotalPageFile;     // Size of the committed memory limit, in bytes.
              public uint dwAvailPageFile;     // Size of available memory to commit, in bytes.
              public uint dwTotalVirtual; // Total size of the user mode portion of the virtual address space of the calling process, in bytes.
              public uint dwAvailVirtual; // Size of unreserved and uncommitted memory in the user mode portion of the virtual address space of the calling process, in bytes.
         }
 
         [DllImport("kernel32.dll", EntryPoint="GlobalMemoryStatus")]
         public static extern void GlobalMemoryStatus (
              ref MemoryStruct lpBuffer
              );
 
         public MemoryHelper()
         {
              //
              // TODO: 在此处添加构造函数逻辑
              //
         }
 
         ///<summary>
         ///获取百分(%)之几的内存正在被使用
         ///</summary>
         ///<returns></returns>
         public static uint GetMemoryLoad()
         {
              MemoryStruct MemInfo = new MemoryStruct();
              GlobalMemoryStatus(ref MemInfo);
 
              return MemInfo.dwMemoryLoad;
         }
 
         ///<summary>
         ///获取物理内存的大小
         ///</summary>
         ///<returns></returns>
         public static uint GetTotalPhysicalMemory()
         {
              MemoryStruct MemInfo = new MemoryStruct();
              GlobalMemoryStatus(ref MemInfo);
 
              return MemInfo.dwTotalPhys;
         }
 
         ///<summary>
         ///获取可用物理内存的大小
         ///</summary>
         ///<returns></returns>
         public static uint GetAvailablePhysicalMemory()
         {
              MemoryStruct MemInfo = new MemoryStruct();
              GlobalMemoryStatus(ref MemInfo);
 
              return MemInfo.dwAvailPhys;
         }
 
         ///<summary>
         ///获取交换文件总大小
         ///</summary>
         ///<returns></returns>
         public static uint GetTotalPageFileSize()
         {
              MemoryStruct MemInfo = new MemoryStruct();
              GlobalMemoryStatus(ref MemInfo);
 
              return MemInfo.dwTotalPageFile;
         }
     }
}
 
四、             运行效果
五、             小结
编写小工具来解决日常问题是一件非常有趣的事情,同时也可以提高工作效率。本文的吃内存工具通过调用Windows API来获得系统内存使用情况,如果读者感兴趣,可以使用那些API接口来获取更多的内存信息(包括虚拟内存)。
 

Linux C 吃内存的程序

网上的吃内存的例子,不实用,有的不符合要求,自己写了一个吃内存的c程序,这个程序用了两个进程,一个是吃内存的进程,另一个是专门打印内存使用情况的进程。一开始用一个进程,发现没有达到迅速吃内存的效果,可...
  • maokexu123
  • maokexu123
  • 2015年10月30日 16:40
  • 538

.Net MVC4 被坑心得 (九) WebApi下的数据级缓存

使用webapi做rest的服务接口时,有些读取数据表的操作,数据本身变化不频繁,但是访问量却不小,比如频道分类,地市选择信息等等等等。这时,必然想到使用缓存。     在普通controller下,...
  • sslyc8991
  • sslyc8991
  • 2013年09月26日 17:28
  • 7257

小心服务器内存居高不下的元凶----WebAPI服务

内存这东西虽然便宜,白菜价,但实际在我们的互联网环境中还是非常珍贵的资源,谁叫它不能像硬盘似的,随便弄一块就有好几百G,而没内存就准备挂吧! 话说回来,这次分享的主要是我们在使用调用WebAPI 时...
  • jivenbest
  • jivenbest
  • 2012年07月26日 11:25
  • 1441

一个快速消耗内存的小程序

#include #include using namespace std; void main() { int i=0; double *a=NULL; while(true...
  • yang15225094594
  • yang15225094594
  • 2012年07月30日 20:35
  • 1259

为什么Java程序占用的内存比实际分配给它的要多

转自: http://www.oschina.net/question/100267_65544 很多人错误的认为运行Java程序时使用-Xmx和-Xms参数指定的就是程序将会占用的内存,但是这...
  • cloudeagle_bupt
  • cloudeagle_bupt
  • 2015年02月21日 22:35
  • 1200

C# Winform应用程序占用内存较大解决方法整理

背景: 微软的 .NET FRAMEWORK 现在可谓如火如荼了。但是,.NET 一直所为人诟病的就是“胃口太大”,狂吃内存,虽然微软声称 GC 的功能和智能化都很高,但是内存的回收问题,一直存...
  • Draling
  • Draling
  • 2015年01月13日 11:34
  • 2977

C语言实现贪吃蛇(四)----游戏存档读档(文件操作)

前言:对于C语言的初学者来说,可能会觉得文件操作是一个比较陌生的领域,但实际上无论编写怎样的程序文件操作都是必需的。在操作系统中,所有的外围设备(包括键盘和显示器)都被看作是文件系统中的文件,因此所有...
  • baidu_30000217
  • baidu_30000217
  • 2016年11月18日 19:50
  • 2868

完整的内存设备驱动程序

  • 2013年07月05日 22:23
  • 125KB
  • 下载

一个我自己做的小工具<模拟按键、查看内存、查看应用程序内容等>

  • 2009年07月21日 22:32
  • 224KB
  • 下载

使用消息队列与共享内存完成一个简单的终端聊天程序

  • 2016年08月09日 23:36
  • 459KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:一个完整的吃内存程序
举报原因:
原因补充:

(最多只允许输入30个字)