激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - C# - 詳解C#獲取特定進程CPU和內存使用率

詳解C#獲取特定進程CPU和內存使用率

2021-12-10 14:07maowang C#

本篇文章主要介紹詳解C#獲取特定進程CPU和內存使用率,非常具有實用價值,需要的朋友可以參考下。

首先是獲取特定進程對象,可以使用Process.GetProcesses()方法來獲取系統中運行的所有進程,或者使用Process.GetCurrentProcess()方法來獲取當前程序所對應的進程對象。當有了進程對象后,可以通過進程對象名稱來創建PerformanceCounter類型對象,通過設定PerformanceCounter構造函數的參數實現獲取特定進程的CPU和內存使用情況。

具體實例代碼如下:

首先是獲取本機中所有進程對象,分別輸出某一時刻各個進程的內存使用情況:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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  
  }
}

然后是執行代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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

 以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
  • C#C#裁剪,縮放,清晰度,水印處理操作示例

    C#裁剪,縮放,清晰度,水印處理操作示例

    這篇文章主要為大家詳細介紹了C#裁剪,縮放,清晰度,水印處理操作示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    吳 劍8332021-12-08
  • C#C#實現XML文件讀取

    C#實現XML文件讀取

    這篇文章主要為大家詳細介紹了C#實現XML文件讀取的相關代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    Just_for_Myself6702022-02-22
  • C#WPF 自定義雷達圖開發實例教程

    WPF 自定義雷達圖開發實例教程

    這篇文章主要介紹了WPF 自定義雷達圖開發實例教程,本文介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下...

    WinterFish13112021-12-06
  • C#C# 實現對PPT文檔加密、解密及重置密碼的操作方法

    C# 實現對PPT文檔加密、解密及重置密碼的操作方法

    這篇文章主要介紹了C# 實現對PPT文檔加密、解密及重置密碼的操作方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下...

    E-iceblue5012022-02-12
  • C#深入解析C#中的交錯數組與隱式類型的數組

    深入解析C#中的交錯數組與隱式類型的數組

    這篇文章主要介紹了深入解析C#中的交錯數組與隱式類型的數組,隱式類型的數組通常與匿名類型以及對象初始值設定項和集合初始值設定項一起使用,需要的...

    C#教程網6172021-11-09
  • C#C#設計模式之Visitor訪問者模式解決長隆歡樂世界問題實例

    C#設計模式之Visitor訪問者模式解決長隆歡樂世界問題實例

    這篇文章主要介紹了C#設計模式之Visitor訪問者模式解決長隆歡樂世界問題,簡單描述了訪問者模式的定義并結合具體實例形式分析了C#使用訪問者模式解決長...

    GhostRider9502022-01-21
  • C#C#通過KD樹進行距離最近點的查找

    C#通過KD樹進行距離最近點的查找

    這篇文章主要為大家詳細介紹了C#通過KD樹進行距離最近點的查找,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    帆帆帆6112022-01-22
  • C#Unity3D實現虛擬按鈕控制人物移動效果

    Unity3D實現虛擬按鈕控制人物移動效果

    這篇文章主要為大家詳細介紹了Unity3D實現虛擬按鈕控制人物移動效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一...

    shenqingyu060520232410972022-03-11
主站蜘蛛池模板: 国产黄色毛片 | 久久久久久久久久久久久久av | 色播一区 | 免费国产一级特黄久久 | 国产精选久久 | 深夜激情视频 | 福利一区二区三区视频在线观看 | 在火车上摸两乳爽的大叫 | 国产91av视频| 色999国产 | 久久综合久久精品 | 欧美另类综合 | 久久草草亚洲蜜桃臀 | 成人福利视频在 | 成人在线视频在线观看 | 久欧美| www.精品在线 | 可以看逼的视频 | 黄色免费小视频网站 | 91免费在线视频 | 视频在线中文字幕 | 色综合久久久久综合99 | 国产手机国产手机在线 | 国产视频第一区 | 国产精品久久久久久久久久久天堂 | 黄色伊人网站 | 亚洲 综合 欧美 动漫 丝袜图 | 一级毛片免费观看 | 国产一级午夜 | 国产精品久久久久久久四虎电影 | 免费一级毛片在线播放不收费 | a免费毛片| 亚洲福利视频52 | 宅男噜噜噜66国产在线观看 | 久久久精彩 | 成人精品久久 | 久久精品网 | 午夜精品在线视频 | 久草在线视频网 | 国产毛片aaa一区二区三区视频 | 俄罗斯16一20sex牲色另类 |