您好,登錄后才能下訂單哦!
監控每個進程占用的cpu,比如任務管理器的進程tab中的CPU
在代碼里,可以通過新建PerformanceCounter來建立監控,其對應的Windows中的自帶性能分析工具Perfmon
看下該類的定義中,只要有三個概念:
categoryName:
The name of the performance counter category (performance object) with which
this performance counter is associated.
counterName:
The name of the performance counter.
instanceName:
The name of the performance counter category instance, or an empty string
(""), if the category contains a single instance.
其對應關系如下:
由于instance是變化的,所以每次要根據Process得到instance,那么process跟instance間的關系如何,請看:
PerformanceCounter("Process", "ID Process", instance)這個指標取NextValue()就是ProcessID,就可以跟Process對應起來
但是注意,每個Catagory下面的instance都是不同的,所有Process下的instance到其他Category下就不識別了。
獲取instance代碼如下:
public static string GetInstanceName(string categoryName, string counterName, Process p) { try { PerformanceCounterCategory processcounter = new PerformanceCounterCategory(categoryName); string[] instances = processcounter.GetInstanceNames(); foreach (string instance in instances) { PerformanceCounter counter = new PerformanceCounter(categoryName, counterName, instance); //Logger.Info("對比in mothod GetInstanceName," + counter.NextValue() + ":" + p.Id); if (counter.NextValue() == p.Id) { return instance; } } } catch (Exception ex) { } return null; }
獲取cpu占用率的PerformanceCounter:
string instance1 = GetInstanceName("Process", "ID Process", p); if (instance1 != null) { PerformanceCounter cpucounter = new PerformanceCounter("Process", "% Processor Time", instance1); if (cpucounter != null) { cpucounter.NextValue(); System.Threading.Thread.Sleep(200); //等200ms(是測出能換取下個樣本的最小時間間隔),讓后系統獲取下一個樣本,因為第一個樣本無效 return cpucounter; } else { Logger.Info("Name:" + name + "生成CPU監控失敗" + instance1); } } else { Logger.Info("Name:" + name + "獲取cpu監控實例失敗" + instance1); }
獲取GC占用率的PerformanceCounter:
GC選取了PerformanceCounter(".NET CLR Memory", "% Time in GC", instance2)這個counter,但注意,這兩個屬于不同Category,所以instance不能共用
代碼如下:
// 獲取GC占用率 PerformanceCounter string instance2 = GetInstanceName(".NET CLR Memory", "Process ID", p); if (instance2 != null) { PerformanceCounter gccounter = new PerformanceCounter(".NET CLR Memory", "% Time in GC", instance2); if (gccounter != null) { return gccounter; Logger.Info("Name:" + name + "生成GC監控成功" + instance2); } else { Logger.Info("Name:" + name + "生成GC監控失敗" + instance2); } } else { Logger.Info("Name:" + name + "獲取GC監控實例失敗" + instance2); }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。