CPU使用率是如何计算的?

发布于 2024-09-24 17:33:46 字数 138 浏览 2 评论 0原文

在我的桌面上,有一个小部件可以告诉我当前的 CPU 使用情况。它还显示了我的两个核心的使用情况。

我一直想知道,CPU如何计算其处理能力的使用量?另外,如果 CPU 挂起执行一些密集的计算,它(或处理此活动的任何内容)如何检查使用情况,而不挂起?

On my desktop, I have a little widget that tells me my current CPU usage. It also shows the usage for each of my two cores.

I always wondered, how does the CPU calculate how much of its processing power is being used? Also, if the CPU is hung up doing some intense calculations, how can it (or whatever handles this activity) examine the usage, without getting hung up as well?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

洒一地阳光 2024-10-01 17:33:46

有一个称为空闲任务的特殊任务,它在没有其他任务可以运行时运行。使用百分比只是我们不运行空闲任务的时间百分比。操作系统将保留运行空闲任务所花费的时间的运行总计:

  • 当我们切换到空闲任务时,设置 t = 当前时间
  • 当我们从空闲任务切换时,将(当前时间 - t)添加到运行总计

如果我们对运行总时间的两个样本相隔 n 秒,我们可以将运行空闲任务所花费的 n 秒的百分比计算为(第二个样本 - 第一个样本)/n

请注意,这是操作系统而不是 CPU 所做的事情。 CPU级别不存在任务的概念! (实际上,空闲任务会通过 HLT 指令让处理器进入睡眠状态,因此 CPU 确实知道它何时不被使用)

至于第二个问题,现代操作系统是抢占式多任务的,这意味着操作系统可以随时离开您的任务。操作系统实际上是如何从你的任务中窃取 CPU 的?中断:http://en.wikipedia.org/wiki/Interrupt

There's a special task called the idle task that runs when no other task can be run. The % usage is just the percentage of the time we're not running the idle task. The OS will keep a running total of the time spent running the idle task:

  • when we switch to the idle task, set t = current time
  • when we switch away from the idle task, add (current time - t) to the running total

If we take two samples of the running total n seconds apart, we can calculate the percentage of those n seconds spent running the idle task as (second sample - first sample)/n

Note that this is something the OS does, not the CPU. The concept of a task doesn't exist at the CPU level! (In practice, the idle task will put the processor to sleep with a HLT instruction, so the CPU does know when it isn't being used)

As for the second question, modern operating systems are preemptively multi-tasked, which means the OS can switch away from your task at any time. How does the OS actually steal the CPU away from your task? Interrupts: http://en.wikipedia.org/wiki/Interrupt

一腔孤↑勇 2024-10-01 17:33:46

CPU 本身不进行使用率计算。它可能具有使该任务变得更容易的硬件功能,但这主要是操作系统的工作。显然,实现的细节会有所不同(特别是在多核系统的情况下)。

总体思路是看看CPU需要做的事情的队列有多长。操作系统可以定期查看调度程序以确定它必须做的事情的数量。

这是 Linux 中执行上述计算的函数(摘自维基百科)

#define FSHIFT   11  /* nr of bits of precision */
#define FIXED_1  (1<<FSHIFT) /* 1.0 as fixed-point */
#define LOAD_FREQ (5*HZ) /* 5 sec intervals */
#define EXP_1  1884  /* 1/exp(5sec/1min) as fixed-point */
#define EXP_5  2014  /* 1/exp(5sec/5min) */
#define EXP_15 2037  /* 1/exp(5sec/15min) */

#define CALC_LOAD(load,exp,n) \
    load *= exp; \
    load += n*(FIXED_1-exp); \
    load >>= FSHIFT;

unsigned long avenrun[3];

static inline void calc_load(unsigned long ticks)
{
    unsigned long active_tasks; /* fixed-point */
    static int count = LOAD_FREQ;

    count -= ticks;
    if (count < 0) {
        count += LOAD_FREQ;
        active_tasks = count_active_tasks();
        CALC_LOAD(avenrun[0], EXP_1, active_tasks);
        CALC_LOAD(avenrun[1], EXP_5, active_tasks);
        CALC_LOAD(avenrun[2], EXP_15, active_tasks);
    }
}

至于问题的第二部分,大多数现代操作系统都是多任务。这意味着操作系统不会让程序占用所有处理时间并且本身没有任何时间(除非您这样做)。换句话说,即使应用程序出现挂起,操作系统仍然可以窃取一些时间来完成自己的工作。

The CPU doesn't do the usage calculations by itself. It may have hardware features to make that task easier, but it's mostly the job of the operating system. So obviously the details of implementations will vary (especially in the case of multicore systems).

The general idea is to see how long is the queue of things the CPU needs to do. The operating system may take a look at the scheduler periodically to determine the number of things it has to do.

This is a function Linux in (ripped from Wikipedia) that performs said calculation:

#define FSHIFT   11  /* nr of bits of precision */
#define FIXED_1  (1<<FSHIFT) /* 1.0 as fixed-point */
#define LOAD_FREQ (5*HZ) /* 5 sec intervals */
#define EXP_1  1884  /* 1/exp(5sec/1min) as fixed-point */
#define EXP_5  2014  /* 1/exp(5sec/5min) */
#define EXP_15 2037  /* 1/exp(5sec/15min) */

#define CALC_LOAD(load,exp,n) \
    load *= exp; \
    load += n*(FIXED_1-exp); \
    load >>= FSHIFT;

unsigned long avenrun[3];

static inline void calc_load(unsigned long ticks)
{
    unsigned long active_tasks; /* fixed-point */
    static int count = LOAD_FREQ;

    count -= ticks;
    if (count < 0) {
        count += LOAD_FREQ;
        active_tasks = count_active_tasks();
        CALC_LOAD(avenrun[0], EXP_1, active_tasks);
        CALC_LOAD(avenrun[1], EXP_5, active_tasks);
        CALC_LOAD(avenrun[2], EXP_15, active_tasks);
    }
}

As for the second part of your question, most modern operating systems are multi-tasked. That means the OS is not going to let programs take up all the processing time and not have any for itself (unless you make it do that). In other words, even if an application appears hung, the OS can still steal some time away for its own work.

烟酉 2024-10-01 17:33:46

要获取 CPU 使用率,请定期对进程时间进行采样,并找出差异。

例如,如果这些是进程 1 的 CPU 时间:

kernel: 1:00:00.0000
user:   9:00:00.0000

然后两秒后再次获取它们,它们是:

kernel: 1:00:00.0300
user:   9:00:00.6100

减去内核时间(相差 0.03)和用户时间(0.61),将它们相加 (0.64),然后除以 2 秒的采样时间 (0.32)。

因此在过去两秒内,该进程平均使用了 32% 的 CPU 时间。

获取此信息所需的特定系统调用在每个平台上(显然)是不同的。在 Windows 上,您可以使用 GetProcessTimes,或 < a href="http://msdn.microsoft.com/en-us/library/ms724400(VS.85).aspx" rel="noreferrer">GetSystemTimes(如果您想要总计的快捷方式) 已使用或空闲的CPU时间。

To get CPU usage, periodically sample the total process time, and find the difference.

For example, if these are the CPU times for process 1:

kernel: 1:00:00.0000
user:   9:00:00.0000

And then you obtain them again two seconds later, and they are:

kernel: 1:00:00.0300
user:   9:00:00.6100

You subtract the kernel times (for a difference of 0.03) and the user times (0.61), add them together (0.64), and divide by the sample time of 2 seconds (0.32).

So over the past two seconds, the process used an average of 32% CPU time.

The specific system calls needed to get this info are (obviously) different on every platform. On Windows, you can use GetProcessTimes, or GetSystemTimes if you want a shortcut to total used or idle CPU time.

晨光如昨 2024-10-01 17:33:46

一种方法如下:

选择一个采样间隔,例如实际运行时间的每 5 分钟(300 秒)一次。您可以从 gettimeofday 获取此信息。

获取您在这 300 秒内使用的处理时间。您可以使用 times() 调用来获取它。这将是 new_process_time - old_process_time,其中 old_process_time 是您从上次时间间隔保存的进程时间。

您的 CPU 百分比为 (process_time/elapsed_time)*100.0
您可以设置一个警报,每 300 秒发出一次信号来进行这些计算。

我有一个进程,我不想使用超过特定目标 cpu 百分比的进程。这种方法效果很好,并且与我的系统监视器非常吻合。如果我们使用太多的CPU,我们会睡一会儿。

One way to do it is as follows:

Pick a sampling interval, say every 5 min (300 seconds) of real elapsed time. You can get this from gettimeofday.

Get the process time you've used in that 300 seconds. You can use the times() call to get this. That would be the new_process_time - old_process_time, where old_process_time is the process time you saved from the last time interval.

Your cpu percentage is then (process_time/elapsed_time)*100.0
You can set an alarm to signal you every 300 seconds to make these calculations.

I have a process that I do not want to use more than a certain target cpu percentage. This method works pretty good, and agrees well with my system monitor. If we're using too much cpu, we usleep for a little.

夜雨飘雪 2024-10-01 17:33:46

这是我接触过类似代码后的基本理解。任务管理器等程序或小部件访问 NtQuerySystemInformation() 等系统调用,并使用从操作系统收集的信息来简单计算 CPU 空闲或正在使用的时间百分比(在标准时间量内)。 CPU 知道它何时空闲,因此它可以确定何时不空闲。这些程序确实会被堵塞……我的破旧笔记本电脑的任务管理器在计算 CPU 使用率达到 100% 时始终冻结。

可以在 MSDN 网站上找到一些很酷的示例代码,其中显示了计算一组指令的 CPU 使用率的函数调用:http://msdn.microsoft.com/en-us/library/aa364157(VS.85).aspx

这些系统调用的作用是访问内核代码我相信……这超出了我的理解范围。

This is my basic understanding from having a little exposure to similar code. Programs like Task Manager or your widget access system calls like NtQuerySystemInformation() and use the information gathered from the OS to make the simple calculation of the percent of time a CPU is idle or being used (in a standard amount of time). A CPU knows when it is idle so it can therefore determine when it's not idle. These programs can indeed get clogged up...my crummy laptop's Task Manager freezes all the time when calculating CPU usage when it's topping out at 100%.

A cool bit of example code can be found on MSDNs website that shows function calls for calculating CPU usage for a set of instructions: http://msdn.microsoft.com/en-us/library/aa364157(VS.85).aspx

What these system calls do is access kernel code I believe... which is beyond the scope of my understanding.

梦回梦里 2024-10-01 17:33:46

有多种方法可以做到这一点:

处理器维护多个衡量性能的计数器,您可以使用 Papi 接口访问它们。例如,这里有一个简短的介绍: http://blogs.oracle.com/jonh/entry/ Performance_counter_generic_events

还:http://www.drdobbs.com/tools/184406109

你可能想要的计数器是 PAPI_TOT_CYC 这是繁忙周期的数量(如果我没记错的话)

there is a number of ways you can do it:

Processor maintains several counters which measure performance, you can access them using Papi interface. for example here is a brief introduction: http://blogs.oracle.com/jonh/entry/performance_counter_generic_events

also: http://www.drdobbs.com/tools/184406109

the counter you may want is PAPI_TOT_CYC which is number of busy cycles (if I remember correctly)

如痴如狂 2024-10-01 17:33:46

嗯,据我了解,

while(true){}

操作系统有一个巨大的循环。您的流程是在该循环内进行管理的。它允许外部代码直接在处理器上以块的形式执行。毫不夸张地说,这是对实际情况的超级简化。

Well, as far as I understand it there's a giant

while(true){}

loop that the operating systems spins up. Your process is managed from within that loop. It allows external code to be executed directly on the processor in chunks. Without exaggerating too much, this is an uber-simplification of what is actually going on.

小兔几 2024-10-01 17:33:46
  1. CPU 不会“挂起”,它只是以峰值容量运行,这意味着它每秒处理的指令数量与其物理能力相同。
    计算 CPU 使用率的进程就是其中一些指令。如果应用程序尝试以比 CPU 能力更快的速度执行操作,那么它们就会被延迟,从而导致“挂起”。

  2. CPU 利用率的计算基于总可用利用率。因此,如果一个 CPU 有两个核心,其中一个核心的使用率为 30%,另一个核心的使用率为 60%,则总体利用率为 45%。您还可以查看每个核心的使用情况。

  1. The CPU does not get 'hung' up, it is simply operating at peak capacity, meaning it is processing as many instructions as it is physically capable every second.
    The process that is calculating CPU usage is some of those instructions. If applications try to do operations faster than the CPU is capable, then simply they will be delayed, hence the 'hung up'.

  2. The calculation of CPU utilization is based on the total available utilization. So if a CPU has two cores, and one core has 30% usage, and the other is 60%, the overall utilization is 45%. You can also see the usage of each individual core.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文