Get certain Processor CPU usage using C# -


i google these code processor cpu usage

       int processorcount = environment.processorcount;        performancecounter myappcpu =  new performancecounter( "process", "% processor time", "chrome", true);         float cpuusage = myappcpu.nextvalue() / processorcount; 

but in taskmanager,one disk image may have multi pids

enter image description here

so,i want know ,is cpu usage code counted total usage chrome browser?

you can use getprocesstimes function kernel32.dll. see .net usage here: http://www.pinvoke.net/default.aspx/kernel32/getprocesstimes.html

the first parameter handle of process. use either system.diagnostics.process.getcurrentprocess().handle or system.diagnostics.process.getprocessbyid(123).handle or other process instance.

using system; using system.collections.generic; using system.componentmodel; using system.linq; using system.runtime.interopservices; using system.runtime.interopservices.comtypes; using system.text; using system.threading; using system.threading.tasks;  namespace cpuusage {     class program {     static void main(string[] args)     {         var status = new cpustatus(system.diagnostics.process.getcurrentprocess());         console.writeline("cpu usage: {0}", status.rawusage);          var processes = system.diagnostics.process.getprocessesbyname("devenv");         if (processes.any())         {             var status2 = new cpustatus(processes.first());             console.writeline("devenv cpu usage: {0}", status.rawusage);              thread.sleep(1000);              console.writeline("devenv cpu usage: {0}", status.rawusage);         }     } }  /// <summary> /// class retrieve cpu values. /// </summary> /// <remarks></remarks> public class cpustatus {      #region "members"     private processtimes _processtimes = new processtimes();     private long _oldusertime;     private long _oldkerneltime;     private datetime _oldupdate;     private int32 _rawusage;             private object _lock = new object();     private intptr _processhandle;     #endregion      #region "constructor"     /// <summary>     /// initializes cpustatus instance     /// </summary>     /// <param name="process">the process monitor</param>     public cpustatus(system.diagnostics.process process)     {         _oldupdate = datetime.minvalue;                   _processhandle = process.handle;          initvalues();     }     #endregion      #region imports     [dllimport("kernel32.dll", setlasterror = true)]     [return:marshalas(unmanagedtype.bool)]     static extern bool getprocesstimes(intptr hprocess, out long lpcreationtime, out long lpexittime, out long lpkerneltime, out long lpusertime);     #endregion      #region "private methods"     /// <summary>     /// retrieve initial values     /// </summary>     /// <remarks></remarks>     private void initvalues()     {         try         {              if ((getprocesstimes(_processhandle, out _processtimes.rawcreationtime, out _processtimes.rawexittime, out _processtimes.rawkerneltime, out _processtimes.rawusertime)))             {                 // convert values datetime values                 _processtimes.converttime();                  _oldusertime = _processtimes.usertime.ticks;                 _oldkerneltime = _processtimes.kerneltime.ticks;                 _oldupdate = datetime.now;             }         }         catch (exception)         {             _oldupdate = datetime.minvalue;         }     }      /// <summary>     /// refreshes usage values     /// </summary>     /// <remarks></remarks>     private void refresh()     {         lock (_lock)         {              if ((getprocesstimes(_processhandle, out _processtimes.rawcreationtime, out _processtimes.rawexittime, out _processtimes.rawkerneltime, out _processtimes.rawusertime)))             {                 // convert values datetime values                 _processtimes.converttime();                  updatecpuusage(_processtimes.usertime.ticks, _processtimes.kerneltime.ticks);             }             else             {                 throw new win32exception(marshal.getlastwin32error(), "could not retrieve process times");             }         }     }      /// <summary>     /// updates cpu usage (cpu usgae = usertime + kerneltime)     /// </summary>     /// <param name="newusertime"></param>     /// <param name="newkerneltime"></param>     /// <remarks></remarks>     private void updatecpuusage(long newusertime, long newkerneltime)     {         long updatedelay = 0;         long usertime = newusertime - _oldusertime;         long kerneltime = newkerneltime - _oldkerneltime;          if (_oldupdate == datetime.minvalue)         {             _rawusage = convert.toint32((usertime + kerneltime) * 100);         }         else         {             // eliminates "divided zero"             if (datetime.now.ticks == _oldupdate.ticks)                 thread.sleep(100);              updatedelay = datetime.now.ticks - _oldupdate.ticks;              _rawusage = convert.toint32(((usertime + kerneltime) * 100) / updatedelay);         }          _oldusertime = newusertime;         _oldkerneltime = newkerneltime;         _oldupdate = datetime.now;     }     #endregion      #region "properties"     /// <summary>     /// gets cpu usage     /// </summary>     /// <value></value>     /// <returns></returns>     /// <remarks></remarks>     public int32 rawusage     {                 {             lock (_lock)             {                 refresh();                 return _rawusage;             }         }     }     #endregion      #region "internal classes"     private struct processtimes     {         public datetime creationtime;         public datetime exittime;         public datetime kerneltime;         public datetime usertime;          public long rawcreationtime;         public long rawexittime;         public long rawkerneltime;         public long rawusertime;          public void converttime()         {             creationtime = filetimetodatetime(rawcreationtime);             exittime = filetimetodatetime(rawexittime);             kerneltime = filetimetodatetime(rawkerneltime);             usertime = filetimetodatetime(rawusertime);         }          private datetime filetimetodatetime(long filetime)         {             try             {                 return datetime.fromfiletimeutc(filetime);             }             catch (exception)             {                 return new datetime();             }         }     }     #endregion  }  } 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -