欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-31 22:14:58
首先是获取特定进程对象,可以使用process.getprocesses()方法来获取系统中运行的所有进程,或者使用process.getcurrentprocess()方...

首先是获取特定进程对象,可以使用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 构造函数
    /// <summary>
    /// 构造函数,初始化计数器等
    /// </summary>
    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个数
    /// <summary>
    /// 获取cpu个数
    /// </summary>
    public int processorcount
    {
      get
      {
        return m_processorcount;
      }
    }
    #endregion

    #region cpu占用率
    /// <summary>
    /// 获取cpu占用率
    /// </summary>
    public float cpuload
    {
      get
      {
        return pccpuload.nextvalue();
      }
    }
    #endregion

    #region 可用内存
    /// <summary>
    /// 获取可用内存
    /// </summary>
    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 物理内存
    /// <summary>
    /// 获取物理内存
    /// </summary>
    public long physicalmemory
    {
      get
      {
        return m_physicalmemory;
      }
    }
    #endregion

    #region 结束指定进程
    /// <summary>
    /// 结束指定进程
    /// </summary>
    /// <param name="pid">进程的 process id</param>
    public static void endprocess(int pid)
    {
      try
      {
        process process = process.getprocessbyid(pid);
        process.kill();
      }
      catch { }
    }
    #endregion


    #region 查找所有应用程序标题
    /// <summary>
    /// 查找所有应用程序标题
    /// </summary>
    /// <returns>应用程序标题范型</returns>
    public static list<string> findallapps(int handle)
    {
      list<string> apps = new list<string>();

      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和内存使用情况。

原文链接:http://www.cnblogs.com/maowang1991/p/3285983.html

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

上一篇:

下一篇: