Question Performance Counter

JayWeb

Member
Joined
May 27, 2010
Messages
7
Programming Experience
1-3
I am trying to setup performance counters for CPU Usage and Memory Used.
I would like a progress bar and a label to display the percentage.

I have the below code and although it seems to be half working, there is something just not right.. The memory one seems to be working fine although the CPU one is acting strange. Can someone take a look and tell me what might be wrong.


VB.NET:
    Shared perfTotalMemory As New ComputerInfo
    Shared perfFreeMemory As New PerformanceCounter("Memory", "Available MBytes")
    Shared perfProcessorTime As New PerformanceCounter("Processor", "% Processor Time", "_Total")

    Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer.Tick
        Dim totalMemory As Double = perfTotalMemory.TotalPhysicalMemory / 1000000
        Dim freeMemory As Double = (totalMemory - Int(perfFreeMemory.NextValue.ToString())) / totalMemory * 100
        pbRAM.Maximum = totalMemory

        pbCPU.Value = Int(perfProcessorTime.NextValue.ToString())
        pbRAM.Value = totalMemory - Int(perfFreeMemory.NextValue.ToString())
        lblCPU.Text = Format(Int(perfProcessorTime.NextValue.ToString()), "0.0") & "%"
        lblRAM.Text = Format(freeMemory, "0.0") & "%"
    End Sub
 
help said:
The recommended delay time between calls to the NextValue method is one second, to allow the counter to perform the next incremental read.
For example, where timer interval is 1000 (1 second):
VB.NET:
Private Sub CounterTimer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CounterTimer.Tick
    Dim value As Integer = CInt(Me.CPUCounter.NextValue)
    Me.CPUBar.Value = value
    Me.CPULabel.Text = value.ToString & "%"
End Sub
Did you know you can add PerformanceCounter from ToolBox to form in Designer and configure it there?
 
Back
Top