Programing

CPU 사용량은 어떻게 계산됩니까?

crosscheck 2020. 11. 5. 07:43
반응형

CPU 사용량은 어떻게 계산됩니까?


내 데스크톱에는 현재 CPU 사용량을 알려주는 작은 위젯이 있습니다. 또한 두 코어 각각의 사용량을 보여줍니다.

저는 항상 CPU가 처리 능력이 얼마나 사용되고 있는지 어떻게 계산하는지 궁금했습니다. 또한 CPU가 집중적 인 계산을 수행하는 동안 중단 된 경우 중단없이 어떻게 사용량을 조사 할 수 있습니까 (또는이 활동을 처리하는 것이 무엇이든)?


CPU는 자체적으로 사용량 계산을 수행하지 않습니다. 이 작업을 더 쉽게 만드는 하드웨어 기능이있을 수 있지만 대부분은 운영 체제의 작업입니다. 따라서 구현 세부 사항은 다양합니다 (특히 멀티 코어 시스템의 경우).

일반적인 아이디어는 CPU가 수행해야하는 작업의 대기열이 얼마나되는지 확인하는 것입니다. 운영 체제는 스케줄러를 주기적으로 확인하여 수행해야하는 작업의 수를 결정할 수 있습니다.

이것은 다음과 같은 계산을 수행하는 Linux의 함수입니다 (Wikipedia에서 추출) .

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

질문의 두 번째 부분은 대부분의 최신 운영 체제가 멀티 태스킹 입니다. 즉, OS가 프로그램이 모든 처리 시간을 차지하도록 허용하지 않고 자체적으로 수행하지 않는 한 (당신이 그렇게하지 않는 한) 의미 합니다. 즉, 응용 프로그램이 중단 된 것처럼 보이더라도 OS는 자체 작업을 위해 시간을 훔칠 있습니다 .


다른 작업을 실행할 수 없을 때 실행되는 유휴 작업이라는 특수 작업이 있습니다. % 사용량은 유휴 작업을 실행하지 않는 시간의 백분율입니다. OS는 유휴 작업을 실행하는 데 걸린 총 시간을 유지합니다.

  • 유휴 작업으로 전환 할 때 t = 현재 시간으로 설정합니다.
  • 유휴 작업에서 벗어나면 누계에 (현재 시간-t)를 추가합니다.

총 n 초 간격으로 두 개의 샘플을 취하면 유휴 작업을 실행하는 데 걸린 n 초의 비율을 (두 번째 샘플-첫 번째 샘플) / n으로 계산할 수 있습니다.

이것은 CPU가 아니라 OS가하는 일입니다. 작업의 개념은 CPU 수준에서 존재하지 않습니다! (실제로 유휴 작업은 HLT 명령으로 프로세서를 절전 모드로 전환하므로 CPU가 사용되지 않는시기를 알 수 있습니다)

두 번째 질문에 관해서는 최신 운영 체제가 선제 적으로 멀티 태스킹되므로 OS가 언제든지 작업에서 전환 할 수 있습니다. OS가 실제로 작업에서 CPU를 어떻게 훔치나요? 인터럽트 : http://en.wikipedia.org/wiki/Interrupt


CPU 사용량을 얻으려면 주기적으로 프로세스 시간을 샘플링 하고 차이를 찾으십시오.

예를 들어, 이것이 프로세스 1의 CPU 시간 인 경우 :

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

그런 다음 2 초 후에 다시 얻습니다.

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

커널 시간 (차이에 대해 0.03)과 사용자 시간 ( 0.61)을 빼고 함께 더하고 ( 0.64) 2 초의 샘플 시간 ( )으로 나눕니다 0.32.

따라서 지난 2 초 동안 프로세스는 평균 32 %의 CPU 시간을 사용했습니다.

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.


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.


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.


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)


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.


  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.

참고URL : https://stackoverflow.com/questions/3748136/how-is-cpu-usage-calculated

반응형