博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【进程资源】监视进程资源
阅读量:5022 次
发布时间:2019-06-12

本文共 7653 字,大约阅读时间需要 25 分钟。

 

做一个web仪表盘 监控quartz任务的资源消耗情况,先把实现做了。

 

public class SystemInfo      {          private int m_ProcessorCount = 0;   //CPU个数          private PerformanceCounter pcCpuLoad;   //CPU计数器          private long m_PhysicalMemory = 0;   //物理内存            private const int GW_HWNDFIRST = 0;          private const int GW_HWNDNEXT = 2;          private const int GWL_STYLE = (-16);          private const int WS_VISIBLE = 268435456;          private const int WS_BORDER = 8388608;            #region AIP声明          [DllImport("IpHlpApi.dll")]          extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);            [DllImport("User32")]          private extern static int GetWindow(int hWnd, int wCmd);            [DllImport("User32")]          private extern static int GetWindowLongA(int hWnd, int wIndx);            [DllImport("user32.dll")]          private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);            [DllImport("user32", CharSet = CharSet.Auto)]          private extern static int GetWindowTextLength(IntPtr hWnd);          #endregion            #region 构造函数          ///           /// 构造函数,初始化计数器等          ///           public SystemInfo()          {              //初始化CPU计数器              pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");              pcCpuLoad.MachineName = ".";              pcCpuLoad.NextValue();                //CPU个数              m_ProcessorCount = Environment.ProcessorCount;                //获得物理内存              ManagementClass mc = new ManagementClass("Win32_ComputerSystem");              ManagementObjectCollection moc = mc.GetInstances();              foreach (ManagementObject mo in moc)              {                  if (mo["TotalPhysicalMemory"] != null)                  {                      m_PhysicalMemory = long.Parse(mo["TotalPhysicalMemory"].ToString());                  }              }          }          #endregion            #region CPU个数          ///           /// 获取CPU个数          ///           public int ProcessorCount          {              get              {                  return m_ProcessorCount;              }          }          #endregion            #region CPU占用率          ///           /// 获取CPU占用率          ///           public float CpuLoad          {              get              {                  return pcCpuLoad.NextValue();              }          }          #endregion            #region 可用内存          ///           /// 获取可用内存          ///           public long MemoryAvailable          {              get              {                  long availablebytes = 0;                  //ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_PerfRawData_PerfOS_Memory");                  //foreach (ManagementObject mo in mos.Get())                  //{                  //    availablebytes = long.Parse(mo["Availablebytes"].ToString());                  //}                  ManagementClass mos = new ManagementClass("Win32_OperatingSystem");                  foreach (ManagementObject mo in mos.GetInstances())                  {                      if (mo["FreePhysicalMemory"] != null)                      {                          availablebytes = 1024 * long.Parse(mo["FreePhysicalMemory"].ToString());                      }                  }                  return availablebytes;              }          }          #endregion            #region 物理内存          ///           /// 获取物理内存          ///           public long PhysicalMemory          {              get              {                  return m_PhysicalMemory;              }          }          #endregion            #region 结束指定进程          ///           /// 结束指定进程          ///           /// 进程的 Process ID          public static void EndProcess(int pid)          {              try              {                  Process process = Process.GetProcessById(pid);                  process.Kill();              }              catch { }          }          #endregion              #region 查找所有应用程序标题          ///           /// 查找所有应用程序标题          ///           /// 
应用程序标题范型
public static List
FindAllApps(int Handle) { List
Apps = new List
(); int hwCurr; hwCurr = GetWindow(Handle, GW_HWNDFIRST); while (hwCurr > 0) { int IsTask = (WS_VISIBLE | WS_BORDER); int lngStyle = GetWindowLongA(hwCurr, GWL_STYLE); bool TaskWindow = ((lngStyle & IsTask) == IsTask); if (TaskWindow) { int length = GetWindowTextLength(new IntPtr(hwCurr)); StringBuilder sb = new StringBuilder(2 * length + 1); GetWindowText(hwCurr, sb, sb.Capacity); string strTitle = sb.ToString(); if (!string.IsNullOrEmpty(strTitle)) { Apps.Add(strTitle); } } hwCurr = GetWindow(hwCurr, GW_HWNDNEXT); } return Apps; } #endregion }

 

 

private void button2_Click(object sender, EventArgs e)        {                       //获取当前进程对象              Process cur = Process.GetCurrentProcess();                PerformanceCounter curpcp = new PerformanceCounter("Process", "Working Set - Private", cur.ProcessName);              PerformanceCounter curpc = new PerformanceCounter("Process", "Working Set", cur.ProcessName);              PerformanceCounter curtime = new PerformanceCounter("Process", "% Processor Time", cur.ProcessName);                //上次记录CPU的时间              TimeSpan prevCpuTime = TimeSpan.Zero;              //Sleep的时间间隔              int interval = 1000;                PerformanceCounter totalcpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");                SystemInfo sys = new SystemInfo();              const int KB_DIV = 1024;              const int MB_DIV = 1024 * 1024;              const int GB_DIV = 1024 * 1024 * 1024;              while (true)              {                  //第一种方法计算CPU使用率                  //当前时间                  TimeSpan curCpuTime = cur.TotalProcessorTime;                  //计算                  double value = (curCpuTime - prevCpuTime).TotalMilliseconds / interval / Environment.ProcessorCount * 100;                  prevCpuTime = curCpuTime;                    Console.WriteLine("{0}:{1}  {2:N}KB CPU使用率:{3}", cur.ProcessName, "工作集(进程类)", cur.WorkingSet64 / 1024,value);//这个工作集只是在一开始初始化,后期不变                  Console.WriteLine("{0}:{1}  {2:N}KB CPU使用率:{3}", cur.ProcessName, "工作集        ", curpc.NextValue() / 1024,value);//这个工作集是动态更新的                  //第二种计算CPU使用率的方法                  Console.WriteLine("{0}:{1}  {2:N}KB CPU使用率:{3}%", cur.ProcessName, "私有工作集    ", curpcp.NextValue() / 1024,curtime.NextValue()/Environment.ProcessorCount);                  //Thread.Sleep(interval);                    //第一种方法获取系统CPU使用情况                  Console.Write("\r系统CPU使用率:{0}%", totalcpu.NextValue());                  //Thread.Sleep(interval);                    //第二章方法获取系统CPU和内存使用情况                  Console.Write("\r系统CPU使用率:{0}%,系统内存使用大小:{1}MB({2}GB)", sys.CpuLoad, (sys.PhysicalMemory - sys.MemoryAvailable) / MB_DIV, (sys.PhysicalMemory - sys.MemoryAvailable) / (double)GB_DIV);                  Thread.Sleep(interval);              }                Console.ReadLine();                 }

 

转载于:https://www.cnblogs.com/viewcozy/p/4643722.html

你可能感兴趣的文章
MySQL 的性能(下篇)—— 性能优化方法
查看>>
xctf --Hctf2014 Quals write up
查看>>
一个完整的大作业
查看>>
自定义Java Annotations实例以及用Java Reflection来解析自定义的Annotation
查看>>
【ADB命令第三篇】教你删除忘记的密码!
查看>>
Chapter16— A thread's Stack
查看>>
CoreLocation详解
查看>>
Android App 性能评测与调优
查看>>
【电子基础】单片机定时器实用方法总结
查看>>
Prism4文档翻译(第二章 全部内容)
查看>>
智东西公开课干货盘点 | 全方位解析人脸识别商用落地
查看>>
CSS学习笔记(四):布局
查看>>
JAVA 基于TCP协议的一对一,一对多文件传输实现
查看>>
npm install 权限报错
查看>>
3-类组件及事件绑定
查看>>
java实现文件上传下载至ftp服务器
查看>>
配置SSH框架的心得
查看>>
7.6
查看>>
20.Bulk Write Operations-官方文档摘录
查看>>
【经典数据结构】并查集
查看>>