隐藏

C# 通过PerformanceCounter监控获取系统的cpu占用率

发布:2022/11/10 10:52:20作者:管理员 来源:本站 浏览次数:682

使用C# 监控系统的cpu占用率


首先实例化 PerformanceCounter 如下


   C# 获取整体CPU使用率


   public static System.Diagnostics.PerformanceCounter CpuPerformanceCounter = new System.Diagnostics.PerformanceCounter("Processor", "% Processor Time", "_Total");


   C# 获取指定某个进程的CPU使用率


   public static System.Diagnostics.PerformanceCounter CpuPerformanceCounter =new PerformanceCounter("Process", "% Processor Time", "进程名称", true);


调用获取cpu使用率


   var xx = CpuPerformanceCounter.NextValue();


   注意!

   1. 第一次实例化 调用CPU使用率会始终是0 所以第一条数据可以无视

   2. 当获C# 取某个指定进程cpu使用率时会发现和任务管理器显示的差距非常大,这个时候需要用这个数值除以cpu核心数 得到的才和任务管理器接近一致(根据算法不同会有一定差异)