【发布时间】:2014-02-21 09:30:25
【问题描述】:
我正在计算我的几台服务器上的 CPU 使用率。但是计算非常非常慢。
到目前为止,这是我的代码:
While it <= 5
Dim myOptions As New ConnectionOptions
myOptions.Username = _myParameters("user")
myOptions.Password = _myParameters("password")
Dim myRoot As String = "\\" & _myParameters("server") & "\root\cimv2"
Dim myScope As New ManagementScope(myRoot, myOptions)
Dim myQuery As New ObjectQuery(String.Format("select * from Win32_Processor"))
Dim mySearcher As New ManagementObjectSearcher(myScope, myQuery)
Dim myCollection As ManagementObjectCollection = mySearcher.Get
For Each OS As ManagementObject In myCollection
values.Add(OS("LoadPercentage"))
Next
Threading.Thread.Sleep(100) //Set some time between two calculations
itCounter += 1
End While
代码每次都挂起
For Each OS As ManagementObject In myCollection
应用程序在那里损失大约 2-3 秒。如果一个 CPU 没有问题。 但在我们的例子中
-
使用 5 次读取计算平均值
2.5 秒 * 5 = 12.5 秒
-
监控大约 15 个 CPU
12.5 秒 * 15 = 3 分钟
两次更新之间的 3 分钟太长了。
问题:这种延迟的原因和解决方法?
注意:此代码已在另一个线程中运行。
注意 2:最终的 C# 代码也是受欢迎的
解决方案(非常感谢 Jon Egerton)
对于未来的观众,这个解决方案为我解决了这个问题:
Dim logon As New DlaLogon // control used for impersonation
logon.impersonateValidUser(//Impersonate here using username + password)
Dim cpuPerformance As New PerformanceCounter()
cpuPerformance.MachineName = myParameters("server") //myServername
cpuPerformance.CategoryName = "Processor"
cpuPerformance.CounterName = "% Processor Time"
cpuPerformance.InstanceName = "_Total"
// Calculate average over 5 times
While it <= 5
//Add the result to List 'CpuReads'
//We will calculate the average based on that list
cpuReads.Add(cpuPerformance.NextValue())
Threading.Thread.Sleep(500) // sleep for 0.5 sec
it += 1
End While
it = 0
logon.undoImpersonation() // Undo impersonation
希望对你有用
【问题讨论】:
标签: .net vb.net performance cpu-usage performancecounter