我在一个程序中工作,它需要得到当前的CPU使用率,如何在vb.Net中实现这一点,我尝试了4段代码,但每次我仍然得到0%。下面是我使用Link的一个例子
谢谢你,Anes08
发布于 2018-04-17 14:12:53
虽然不允许回答这样的问题,但仍然有一些东西可以帮助你开始:
Dim cpu as New System.Diagnostics.PerformanceCounter
cpu.CategoryName = "Processor"
cpu.CounterName = "% Processor Time"
cpu.InstanceName = "_Total"
MessageBox(cpu.NextValue.ToString + "%")
如果它不起作用,这里有一个更好的版本:
Dim cpu as PerformanceCounter '''Declare in class level
'On form load(actually you need to initialize it first)
cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total")
'''Finally,get the value :
MsgBox(cpu.NextValue & "%") '''Use .ToString if required
发布于 2018-04-17 14:03:32
您可以使用LblCpuUsage.text = CombinedAllCpuUsageOfEachThread.NextValue()
.There是一个帮助程序库来获取该信息:
Performance (参见使用PDH函数使用计数器数据(Windows)^)
。
微软的例子在C中,但也有相应的VB (不是.Net)函数:
Visual Basic (Windows)的性能计数器函数^
发布于 2018-06-21 14:50:35
对我来说,我想要一个平均值。CPU利用率有几个问题,看起来应该有一个简单的包来解决,但我没有看到。
第一个当然是第一个请求的值为0是无用的。既然您已经知道第一个响应是0,为什么函数不考虑这一点并返回真正的.NextValue()呢?
第二个问题是,即时阅读可能是非常不准确的,当你试图作出决定,你的应用程序可能有哪些资源,因为它可能是尖峰,或之间的峰值。
我的解决方案是执行一个for循环,循环并给出过去几秒钟的平均值。您可以调整计数器使其更短或更长(只要它超过2)。
public static float ProcessorUtilization;
public static float GetAverageCPU()
{
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
for (int i = 0; i < 11; ++i)
{
ProcessorUtilization += (cpuCounter.NextValue() / Environment.ProcessorCount);
}
// Remember the first value is 0, so we don't want to average that in.
Console.Writeline(ProcessorUtilization / 10);
return ProcessorUtilization / 10;
}
https://stackoverflow.com/questions/49880183
复制相似问题