计算CPU使用率:代码改进

时间:2014-02-21 09:30:26

标签: .net vb.net performance cpu-usage performancecounter

我在计算几台服务器上的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

我希望它有一些用处

1 个答案:

答案 0 :(得分:5)

System.Diagnostics命名空间包含PerformanceCounter,可用于获取此类信息,而不会实际影响系统。

This answer给出了一个很好的例子。