查询CPU最近一段时间的使用情况
- 查询最近几分钟CPU的平局使用率
- 查询最近几分钟CPU的最高使用率
- 查询最近几分钟CPU使用率高于某一值得占比
我将这三个方法封装了一个CpuUsageHelper
方法,方便使用。
使用PerformanceCounter
对CPU的使用率每隔5秒进行打点,并维护一个LinkedList
存储最近一个小时的CPU打点,使用了ReaderWriterLockSlim
读写锁保护数据的正确性。
下图是一个使用Demo:
(源码获取方式:右键图片另存为之后将后缀改为.zip解压即可获得项目源码)
CpuUsageHelper
类如下:
public static class CpuUsageHelper
{
private const int SampleRate = 5 * 1000; // 5 second
private const int CpuUsageListMaxCapacity = 1 * 60 * 60 * 1000 / SampleRate; // 1 hous capacity.
private static Timer _sampleTimer = null;
private static readonly PerformanceCounter _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
private static readonly LinkedList<float> _cpuUsageList = new LinkedList<float>();
private static