一个完整的吃内存程序

原创 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程序,这个程序用了两个进程,一个是吃内存的进程,另一个是专门打印内存使用情况的进程。一开始用一个进程,发现没有达到迅速吃内存的效果,可...

一个完整的安装程序实例—艾泽拉斯之海洋女神出品(二) --基本设置二

转载自http://www.cnblogs.com/Cindy_weiwei/archive/2009/05/19/1460230.html   7. 点击引导条上的Application Fil...

一个完整的Installshield安装程序实例—艾泽拉斯之海洋女神出品(二) --基本设置二

7. 点击引导条上的Application Files 我们将在这里对安装路径进行微调,并且为每个Feature指定需要安装的文件 这里我不想使用Program Files | C...

探索InstallShield——制作一个完整的应用程序安装实例

大家一定有过这样的经历,每当我们殚精竭虑为用户开发完一个系统之后往往都是派一名技术员到用户那里进行应用软件的安装,数据库的配置,这些看似简单的配置对一般用户来说可不是件容易做的事。这不仅给那些喜欢力求...

基础/Java基础/(2)一个完整的Java程序实例

基础/Java基础/(2)一个完整的Java程序实例

用Installshield制作一个完整程序实例(二)--基本设置(二)

7. 点击引导条上的Application Files 我们将在这里对安装路径进行微调,并且为每个Feature指定需要安装的文件 这里我不想使用Program Files | C...

用Installshield制作一个完整程序实例(一)--基本设置(一)

前言 Installshield可以说是最好的做安装程序的商业软件之一,不过因为功能的太过于强大,以至于上手和精通都不是容易的事情,之前都是用Installshield的Project Assi...

一个完整的Installshield安装程序实例—艾泽拉斯之海洋女神出品(一)---基本设置

前言 Installshield可以说是最好的做安装程序的商业软件之一,不过因为功能的太过于强大,以至于上手和精通都不是容易的事情,之前都是用Installshield的Project Assist...

linux 下如何编写一个完整的应用程序!

步骤如下: 一:编写源码:本文末尾是我自己编写的一个简单的按键应用程序keyFunction.c    二:编译源码:在linux环境下,用对应的toolchain 编译源码,生成应用程序的可执行文件...
  • zchill
  • zchill
  • 2016-10-14 17:37
  • 1799

一个完整的mapreduce程序

package com.hadoop.mapreduce.dc;import java.io.IOException;import org.apache.hadoop.conf.Configurati...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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