Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Thread Cpu Usage

I have a set of cpu consuming executions that each run in thread with low priority. These threads will be run in a Process (Like IIS) that have many other threads that I don't want to slow them. I want to calculate the cpu usage of all other threads and if its greater than 50% then i pause one of my threads, and if its smaller than 50% I resume a paused executions.

In pausing i save the state of execution in db and terminate its thread, and in resuming i start new thread.

What I Need is a function to return the cpu usage percentage of a thread.

private static void monitorRuns(object state)
{
  Process p = Process.GetCurrentProcess;
  double usage = 0;
  foreach(ProcessThread t in p.Threads)
  {
    if(!myThreadIds.Contains(t.Id)) // I have saved my own Thread Ids
    {
      usage += getUsingPercentage(t); // I need a method like getUsingPercentage
    }
  }

  if(usage > 50){
    pauseFirst(); // saves the state of first executions and terminates its threads
  }else{
    resumeFirst(); // start new thread that executes running using a state
  }
}

this function is called with a Timer:

Timer t = new Timer(monitorRuns,null,new TimeSpan(0,0,10),new TimeSpan(0,5,0));
like image 292
mrd abd Avatar asked Oct 15 '25 17:10

mrd abd


1 Answers

To calculate process/thread CPU usage, you should get the processor time of a particular time frame of system/process/thread. And then you can calculate the CPU usage and don't forget to divide the value with the number of CPU cores.

ProcessWideThreadCpuUsage = (ThreadTimeDelta / CpuTimeDelta)
SystemWideThreadCpuUsage = (ThreadTimeDate / CpuTimeDelta) * ProcessCpuUsage
  • To get processor time of a process: Process.TotalProcessorTime API.
  • To get processor time of a thread: ProcessThread.TotalProcessorTime API

I found the example explains the approach. You can read it as a reference.

like image 89
stanleyxu2005 Avatar answered Oct 18 '25 07:10

stanleyxu2005



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!