我正在编写这个类来监控通过所有网络接口的带宽。虽然这整个事情非常好,但我想尝试在查询期间减少 CPU 使用率。原因是因为我每隔几秒钟运行一次,每次都会为进程增加大约 7-8% 的 CPU 使用率。有什么办法可以减少 CPU 周期的数量?
PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
String[] instancename = category.GetInstanceNames();
foreach (string name in instancename)
{
String networkCard = name;
const int numberOfIterations = 10;
PerformanceCounter bandwidthCounter = new PerformanceCounter("Network Interface", "Current Bandwidth", networkCard);
float bandwidth = bandwidthCounter.NextValue();
PerformanceCounter dataSentCounter = new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkCard);
PerformanceCounter dataReceivedCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", networkCard);
float sendSum = 0;
float receiveSum = 0;
for (int index = 0; index < numberOfIterations; index++)
{
sendSum += dataSentCounter.NextValue();
receiveSum += dataReceivedCounter.NextValue();
}
float dataSent = sendSum;
float dataReceived = receiveSum;
double dout = (((8 * (dataSent)) / (bandwidth * numberOfIterations) * 100) * 1024) / 100;
double din = (((8 * (dataReceived)) / (bandwidth * numberOfIterations) * 100) * 1024) / 100;
dout = Math.Round(dout, 2);
din = Math.Round(din, 2);
string doutround = Convert.ToString(dout);
string dinround = Convert.ToString(din);
String output = dinround + "/" + doutround;
GlobalsWMI.NetIOs.Add(output);
}
String tooutput = String.Join("AND", GlobalsWMI.NetIOs);
GlobalsWMI.NetIOs.Clear();
return tooutput;