Reputation: 858
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));
Upvotes: 3
Views: 8664
Reputation: 8241
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
I found the example explains the approach. You can read it as a reference.
Upvotes: 7