获取线程Cpu使用情况 [英] Get Thread Cpu Usage

查看:73
本文介绍了获取线程Cpu使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组消耗CPU的执行,每个执行都以低优先级在线程中运行.这些线程将在具有许多其他线程的进程(如IIS)中运行,而我不想降低它们的速度.我想计算所有其他线程的cpu使用率,如果它的使用率大于50%,则我暂停一个线程,如果它的使用率小于50%,我将恢复暂停的执行.

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.

在暂停时,我将执行状态保存在db中并终止其线程,并在恢复时启动新线程.

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

我需要的是一个返回线程的cpu使用率的函数.

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));

推荐答案

要计算进程/线程的CPU使用率,您应该获取系统/进程/线程的特定时间范围内的处理器时间.然后,您可以计算CPU使用率,并且不要忘记将该值除以CPU内核数.

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

  • 要获取进程的处理器时间: ProcessThread.TotalProcessorTime API
  • 我找到了示例解释了这种方法.您可以阅读它作为参考.

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

    这篇关于获取线程Cpu使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆