This is a simple way to retrieve any performance information from your PC using the .NET framework diagnostics. This demo provides an example of how to retrieve the current % CPU usage on your local computer and output the results to a console window.
This took me a while to figure out, as you may find there are not many to-the-point articles or examples regarding performance monitors. I found many articles describing how to make custom ones but I need to extract the information and store the results.
One use of this code is to perform email alerts to admin persons about processor utilization, memory utilization, etc. (any performance metric) which fall outside a set of parameters indicating something may be going wrong on the machine. Also, by gathering and storing this information over time, you can track your trends on your PC. There is a complementary article I will try to post soon which gives you the code to display the CPU usage/memory usage for all the processes on the PC such as you see in the Task Manager.
Using the code
Start a new Console project (VB.NET) and use the code below.
Public TH1 As New _
Public Sub PerformancMonitor()
Dim bForever As Boolean = False
Dim iFrequency As Integer = 1000
Dim pCounter As System.Diagnostics.PerformanceCounter
Dim sCategory As String = "Processor"
Dim sCounter As String = "% Processor Time"
Dim sInstance As String = "_Total"
Dim Sample As System.Diagnostics.CounterSample
pCounter = New PerformanceCounter
pCounter.CategoryName = sCategory
pCounter.CounterName = sCounter
pCounter.InstanceName = sInstance
Sample = pCounter.NextSample
Do While bForever = False
Dim nv As Single = pCounter.NextValue()
Dim Sample2 As CounterSample = pCounter.NextSample()
Dim avg As Single = CounterSample.Calculate(Sample, Sample2)
Console.WriteLine("% CPU = " & nv.ToString & " -- " & _
"Avg % CPU = " & avg.ToString & _
" , " & Date.Now.ToString)
Catch ex As Exception
Points of interest
Hope this helps, have fun and enjoy!
- Original post - 9-10-2008.