【问题标题】:Calculate CPU-Usage: Code improvement计算 CPU 使用率:代码改进
【发布时间】: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


    【解决方案1】:

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

    This answer 举了一个很好的例子。

    【讨论】:

    • 亲爱的上帝之母!有多大的性能差异!谢谢你!
    • .Net 框架包含大量真正有用的东西。很多时候的问题是意识到你的问题可能已经被框架解决了,然后能够找到它!
    猜你喜欢
    • 2012-06-13
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 2011-04-14
    • 1970-01-01
    相关资源
    最近更新 更多