Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to get CPU Usage using C# .Net

826 views
Skip to first unread message

soumya.dh...@gmail.com

unread,
Jun 6, 2007, 7:03:12 AM6/6/07
to
Hi
I have an C# application in which I am using WMI to obtain CPU
Usage of the total system. I obtain the CPU Usage in % for System Idle
Process and subtract it from 100 to obtain CPU Usage.
Here is the code to obtain CPU Usage

ManagementScope scope = new ManagementScope("root\
\CIMV2");
scope.Options.Impersonation =
ImpersonationLevel.Impersonate;

ManagementObject obj = new ManagementObject();

string strIdle = "Idle";
char b = (char)34; //Double Quotes

string stPath =
"Win32_PerfFormattedData_PerfProc_Process.Name=" + b + strIdle + b;
ManagementPath path = new ManagementPath(stPath);

obj.Path = path;
obj.Scope = scope;
obj.Get();

Debug.Print(obj.Properties["PercentProcessorTime"].Value.ToString ());

I have given this in a while loop to print System Idle Time. But I am
getting 0 always. I searched in google to find something that will
help. I came through the following script.

function abc(x)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")

Set PerfProcess = objWMIService.Get(_
"Win32_PerfFormattedData_PerfProc_Process.Name='idle'")

Dim i
i = 0
While ( i < 20)
PerfProcess.Refresh_
Wscript.Echo PerfProcess.PercentProcessorTime
Wscript.Sleep 1000
i = i+1
Wend
end function

This script is giving me valid Values. I compared with Task Manager
CPU Usage. Now I tried calling this script from my C# code. I created
a ScriptControlClass instance and called the Run method after Adding
the script to the instance. See the code below


MSScriptControl.ScriptControlClass ms;
ms = new MSScriptControl.ScriptControlClass();
ms.AllowUI = true;
ms.Language = "VBScript";
ms.UseSafeSubset = false;
ms.Reset();

string str = rftScript.Text;//This is obtained from my
Form. I am copying
//script to a
Text Box in my form
object[] i = new object[1];
i[0] = "1";
ms.AddCode(str);
object oRes = ms.Run("abc",ref i );

When I run this piece of code it will give me an Exception "Generic
Failure" where ms.Run is called. I commented out
"PerfProcess.Refresh_" in VBscript and then this piece of code works
without any exception. But the problem is again System Idle Process
percentage of CPU time I am getting is 0.

Can anyone tell me a way to refresh the WMI call from C# ? Or how can
I make this VBscript work from C#? Is there any other way to get
percantage of CPU Usage?
Please help me to solve this issue

Regards
Soumya

urkec

unread,
Jun 9, 2007, 4:33:00 PM6/9/07
to

"soumya.dh...@gmail.com" wrote:

There are probably better ways of doing this, but here goes:

using System;
using System.Management;
using System.Threading;
using System.Text;

namespace WMITest
{
class Program
{
static void Main()
{

for (int i = 0; i < 30; i++)
{
ManagementObject processor = new ManagementObject(
"Win32_PerfFormattedData_PerfOS_Processor.Name='_Total'");
processor.Get();

Console.WriteLine(processor.Properties["PercentProcessorTime"].Value);
Thread.Sleep(100); //miliseconds
}
}
}
}


--
urkec


soumya.dh...@gmail.com

unread,
Jun 11, 2007, 8:12:47 AM6/11/07
to
On Jun 10, 1:33 am, urkec <u...@discussions.microsoft.com> wrote:
> urkec- Hide quoted text -
>
> - Show quoted text -

Hi
i solved the issue using following code snippet.

decimal PercentProcessorTime = 0;
m_ManagementPath.RelativePath =
"Win32_PerfRawData_PerfOS_Processor.Name='0'"; //ManagementPath object
m_ManagementObject.Scope = m_ManagementScope; //
ManagementScope object

m_ManagementObject.Path = m_ManagementPath;
m_ManagementObject.Get();

ulong u_oldCPU =
(ulong)m_ManagementObject.Properties["PercentProcessorTime"].Value;//
ManagementObject object
ulong u_oldNano =
(ulong)m_ManagementObject.Properties["TimeStamp_Sys100NS"].Value;

Thread.Sleep(1000);
m_ManagementObject.Get();
ulong u_newCPU =
(ulong)m_ManagementObject.Properties["PercentProcessorTime"].Value;
ulong u_newNano =
(ulong)m_ManagementObject.Properties["TimeStamp_Sys100NS"].Value;


decimal d_newCPU = Convert.ToDecimal(u_newCPU);
decimal d_newNano = Convert.ToDecimal(u_newNano);
decimal d_oldCPU = Convert.ToDecimal(u_oldCPU);
decimal d_oldNano = Convert.ToDecimal(u_oldNano);


if (d_newNano == d_oldNano)
PercentProcessorTime = 0;
else
// Thanks to MSDN for giving me this formula !
PercentProcessorTime = (1 - ((d_newCPU - d_oldCPU) /
(d_newNano - d_oldNano))) * 100m;

// Save the values for the next run
u_oldCPU = u_newCPU;
u_oldNano = u_newNano;
float iRet = -1;
string strPercentProcesssorTime =
PercentProcessorTime.ToString("N", new
System.Globalization.CultureInfo("en-US", false).NumberFormat);
float.TryParse (strPercentProcesssorTime,out iRet );
return iRet;


Thanks n Regards
Soumya

0 new messages