C#获取特定进程CPU和内存使用率

【www.kmfunway.cn--电脑培训】

  首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程对象。当有了进程对象后,可以通过进程对象名称来创建PerformanceCounter类型对象,通过设定PerformanceCounter构造函数的参数实现获取特定进程的CPU和内存使用情况。

  具体实例代码如下:

  首先是获取本机中所有进程对象,分别输出某一时刻各个进程的内存使用情况:

  using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.Threading;namespace CSharpPerformance{//该程序可以实时监控所有进程或者指定进程的工作集、私有工作集 class Program { static void Main(string[] args) { //新建一个Stopwatch变量用来统计程序运行时间 Stopwatch watch = Stopwatch.StartNew(); //获取本机运行的所有进程ID和进程名,并输出哥进程所使用的工作集和私有工作集 foreach (Process ps in Process.GetProcesses()) { PerformanceCounter pf1 = new PerformanceCounter("Process", "Working Set - Private", ps.ProcessName); PerformanceCounter pf2 = new PerformanceCounter("Process", "Working Set", ps.ProcessName); Console.WriteLine("{0}:{1} {2:N}KB", ps.ProcessName, "工作集(进程类)", ps.WorkingSet64 / 1024); Console.WriteLine("{0}:{1} {2:N}KB", ps.ProcessName, "工作集 ", pf2.NextValue() / 1024); //私有工作集 Console.WriteLine("{0}:{1} {2:N}KB", ps.ProcessName, "私有工作集 ", pf1.NextValue() / 1024); } watch.Stop(); Console.WriteLine(watch.Elapsed); Console.ReadLine(); } }}

  其中,工作集ps.WorkingSet64是静态的,pf2.NextValue()是动态变化的,工作集包含进程运行时其独占的内存和与其他进程共享的内存的和,而私有工作集是只包含进程独占的内存。

  下面一组代码可以动态显示本程序所对应的进程的CPU和内存使用率的变化:

  首先是SystemInfo.cs类:

  using System;using System.Collections.Generic;using System.Diagnostics;using System.Threading;using System.IO;using System.Text;using System.Management;using System.Runtime.InteropServices;namespace CSharpPerformance{ 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 IDpublic static void EndProcess(int pid) { try { Process process = Process.GetProcessById(pid); process.Kill(); } catch { } } #endregion #region 查找所有应用程序标题 ///

  /// 查找所有应用程序标题 ///

  ///

  应用程序标题范型

  public static List

  FindAllApps(int Handle) { ListApps = 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 }}

  然后是执行代码:

  using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.Threading;namespace CSharpPerformance{//该程序可以实时监控程序本身对应进程的工作集、私有工作集和CPU使用率 class Program { static void Main(string[] args) { //获取当前进程对象 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(); } }}

  以上程序可以正常运行,没隔1S刷新一次,实现动态显示本程序对应进程的CPU和内存使用情况。

本文来源:https://www.kmfunway.cn/zixuezhishi/14661.html

褚时健 藏宝阁 草料二维码 创客贴 测速 cctv5 csdn cctv5在线直播
  • 相关内容
  • 06-19 win8.1系统怎么截图

    win8 1系统的用户都是用软件自带的截图来截图的,win8 1系统有没有自带的截图工具呢。那么win7系统怎么修改mac地址呢?下面就让jy135小编告诉大家吧。win8 1系统截图方法:1、在Wi电脑

  • 06-19 经营幸福婚姻生活的法则

    导语:想要经营好婚姻,也需要一招一式,今天小编就给大家送上婚姻里的葵花宝典~最近朋友圈都疯传一个段子:以后如果被老公惹生气了,你就这么做!第一招:不要回娘家,报个团旅游去,不要给留任何信息,急死他。第情感

  • 06-19 2017端午节去哪旅游好

    端午节小长假即将到来啦,你们那颗游山玩水的心蠢蠢欲动没?端午节旅游有哪些值得前往的地方,特色景点都有哪些?就让小编为大家介绍吧。2017端午节去哪旅游好湖北秭归秭归县位于中国湖北省宜昌市,县名来源《水旅行

  • 06-19 【九寨沟2017年地震情况】2017端午九寨沟旅游好去处

    五一刚过,端阳将近,端午节假九寨沟去哪玩呢?一起来看看吧。2017端午九寨沟旅游好去处神仙池神仙池是藏语“嫩恩桑措”的汉译,集黄龙及九寨沟之美于一身,意为仙女沐浴的地方。它位于旅行

  • 06-19 小学数学的学习方法

    导语:小学数学知识虽然很基础,但对于很多小学生来说还是有一定的难度的,毕竟小学生之前没有正式接触过数学,所以就更得让小学生掌握良好的学习方法,养成好的学习习惯。接下来,小编为大家介绍小学数学的学习方法教育

  • 热门专题
  • 网站地图- 手机版
  • Copyright @ https://www.kmfunway.cn 据说教育网 All Rights Reserved 京ICP备17136666号
  • 免责声明:据说教育网部分信息来自互联网,并不带表本站观点!若侵害了您的利益,请联系我们,我们将在48小时内删除!