Перейти к содержимому

Cpu utilization что это

  • автор:

% CPU Utilization

Учитывая, что на большинстве платформ есть отдельный счётчик ЦПУ простоя (см. Связанные метрики), советуем использовать следующую формулу для расчета потребления ЦПУ: CPU Consumption = 100 — Idle CPU (%)

Расследование стоит начинать со счётчика Утилизации ЦПУ пользовательского режима, чтобы определить, на что расходуется ресурс ЦПУ: на процессы пользователя или ядра

  • CPU Utilization\%idle (% утилизации ЦПУ во время простоя)
  • CPU Utilization\%usr (% утилизации ЦПУ в пользовательском режиме)
  • CPU Utilization\%sys (% утилизации ЦПУ в системном режиме) (Solaris)
  • Processor\Idle
  • Processor\Kernel (Linux)
  • Processor\%idle
  • Processor\%usr
  • Processor\%sys (AIX)

Примечание: Высокий процент утилизации процессоров на машине не всегда означает наличие проблемы, которую нужно решать. Однако стоит разобраться в причинах, если время простоя ЦПУ ниже 20%, а его падение ниже 10% может свидетельствовать об ошибке.

Метрика загруженности процессора (CPU utiliztion) — это не то что вы думаете

Метрика загруженности процессора (CPU utiliztion), которую все мы привыкли использовать, обычно понимается неправильно. Что такое загруженность процессора? То насколько процессор сейчас занят работой? Нет, это не так, и да, я говорю о метрике %CPU , которая используется всегда и везде, в каждой утилите мониторинга производительности, например в top(1) .

Как вы думаете, что значит нагрузка на процессор 90% на картинке ниже? Вот что это значит на самом деле:

Stalled, то есть “приостановлено” значит, что в данный момент процессор не обрабатывает инструкции, обычно это означает, что он ожидает завершения операций ввода/вывода связанных с памятью (здесь и далее речь о RAM, а не дисковом вводе/выводе). Соотношение между “занято” и “приостановлено” (busy/stalled), которое я привел выше, это то что я обычно вижу в продакшене. Вероятно, что ваш процессор тоже большую часть времени находится в stalled состоянии, но вы об этом и не догадываетесь.

Что это значит для вас? Понимание того насколько много ваш процессор находится в приостановленном состоянии может помочь вам понять куда направить усилия по оптимизации производительности приложения: на ускорение кода или уменьшение числа операций ввода/вывода связанных с памятью. Всем кто заинтересован в оптимизации нагрузки на процессор, в особенности в облаках с настроенным автомасштабированием на основе нагрузки на CPU, будет полезно знать насколько долго процессор находится в приостановленном состоянии.

Что такое нагрузка на процессор на самом деле?

Метрика, которую мы называем нагрузкой на процессор (CPU utilization) на самом деле это “не-idle время”, то есть время, которое процессор не выполняет idle-тред. Ядро вашей операционной системы (какую бы ОС вы не использовали) обычно следит за этим во время переключения контекста. Если не-idle тред запустился, а затем спустя 100 милисекунд остановился, то ядро посчитает, что процессор был использован в течение всего этого времени.

Эта метрика так же стара как и системы совместного использования времени (time sharing systems). В бортовом компьютере лунного модуля Apollo (это пионер среди систем совместного использования времени) idle-тред назывался “DUMMY JOB” и инженеры мониторили циклы выполняющие его в сравнении с реальными задачами, это было важной метрикой измерения нагрузки. (Я писал об этом ранее).

Что же с этой метрикой не так?

В наши дни процессоры работают значительно быстрее памяти, поэтому время ожидания памяти доминирует в метрике “нагрузка на процессор”. Когда вы видите большие значение %CPU в top(1) , вы, должно быть, думаете, что процессор является бутылочным горлышком, когда на самом деле проблема в DRAM.

Со временем все становится только хуже. Долгое время производители процессоров увеличивали тактовые частоты своих процессоров быстрее чем производители памяти уменьшали задержки доступа к памяти (CPU DRAM gap). Примерно в 2005 году процессоры достигли частот в 3 GHz и с тех пор мощность процессоров растет не за счет увеличения тактовой частоты, а за счет большего числа ядер, гипертрединга и многопроцессорных конфигураций. Все это предъявляет еще больше требований к памяти. Производители процессоров пытались снизить задержки связанные с памятью за счет больших по размеру и более умных CPU-кешей, более быстрых шин и соединений. Но проблема со stalled-состоянием все еще не решена.

Как понять, что процессор на самом деле делает

Сделать это можно используя Performance Monitoring Counters (PMC-счетчики): хардверные счетчики, которые могут быть прочитаны с помощью Linux pref (пакет linux-tools-generic в Линуксе) и других утилит. Для примера понаблюдаем за всей системой в течение 10 секунд:

Ключевая метрика здесь instructions per cycle (insns per cycle: IPC, число инструкций за один цикл), которая показывает сколько в среднем инструкций было выполнено за каждый такт. Чем больше, тем лучше. В примере выше значение 0.78 кажется очень неплохим (нагрузка 78%?) до тех пор пока вы не узнаете, что максимальная скорость процессора это IPC 4.0. Такие процессоры называют 4-wide, это название пошло от особенностей пути извлечения/декодирования инструкций в процессоре (подробнее об этом в Википедии).

Это означает, что процессор может выполнить 4 операции за каждый такт, поэтому значение 0.78 для 4-wide системы означает, что процессор работает на 19,5% от своих возможностей. Новый процессор Skylake от Intel — это 5-wide процессор.

Существуют сотни PMC-счетчиков, которые позволяют детальнее разобраться с производительностью системы, например, посчитать число приостановленных циклов по типам.

В облаках

Если вы работаете в виртуальном окружении, то вероятно у вас нет доступа к PMC-счетчикам, это зависит от поддержки этой фичи гипервизором. Я недавно писал о том, что PMC-счетчики теперь доступны в AWS EC2 в виртуальных машинах базирующихся на Xen.

Как интерпретировать и что делать

Если ваш IPC < 1.0 , то вероятнее всего, процессор приостановлен из-за медленной памяти, поэтому нужно оптимизировать софт так, чтобы он требовал меньше операций с памятью, совершенствовать кеширование в процессоре и локальность памяти, особенно в NUMA системах. Оптимизация железа в таком случае подразумевает использование процессоров с большим объемом кешей, более быстрой памятью, шинами и соединениями.

Если ваш IPC > 1.0 , то вероятно, вы ограничены числом инструкций, которые может выполнять процессор. Попробуйте найти способ уменьшить число выполняемых инструкций: уменьшить число ненужной работы, кешировать операции и т.п. CPU flame графы — отличная утилита для этих целей. С точки зрения тюнинга железа, попробуйте использовать процессор с большей тактовой частотой и большим числом ядер и гипертредов.

Для моих правил выше я выбрал значение IPC 1.0, почему именно его? Я пришел к нему из своего опыта работы с PMC-счетчиками. Вы можете выбрать для себя другое значение. Сделайте два тестовых приложения, одно упирающееся по производительности в процессор, другое — в память. Посчитайте IPC для них и возьмите среднее значение.

Что инструменты мониторинга производительности должны сообщать вам?

Каждая такая утилита должны показывать IPC вместе с нагрузкой на процессор. Или разделять нагрузку на процессор на instruction-retired и циклы stalled циклы, то есть, %INS и %STL .

Кроме утилиты top(1) для Линукса есть утилита tiptop(1) , которая показывает IPC для каждого процесса:

Другие причины почему CPU utilization вводит в заблуждение

Проблема со stalled-циклами может быть не только в задержках связанных с памятью:

  • изменение температуры может влиять на приостановленность процессора, может менять тактовую частоту процессора,
  • ядро варьирует частоту процессора с определенным шагом,
  • проблема с усреднением: 80% нагрузки в течение минуты скроет кратковременный всплеск до 100%, : процессор нагружен, имеет высокий IPC, но приложение ничего не делает.

Заключение

Нагрузка на процессор (CPU utilization) это обычно неправильно интерпретируемая метрика, так как она включает циклы, потраченные на ожидание ответа от основной памяти, которые могут доминировать в современных нагрузках. Вы можете понять что на самом деле стоит за %CPU используя дополнительные метрики, включая число инструкций за цикл (IPC). Если IPC < 1.0 , то вероятно вы упираетесь в память, если IPC > 1.0 , то в скорость процессора. Я писал про IPC в своем предыдущем посте, в том числе написал и о использовании PMC-счетчиках, необходимых для измерения IPC.

Инструменты мониторинга производительности, которые показывают %CPU должны показывать PMC-счетчики, чтобы не вводить пользователей в заблуждение. Например, они могут показывать %CPU с IPC и/или число instruction-retired и stalled циклов. Вооруженные этими метриками разработчики и админы могут решить как правильнее тюнинговать их приложения и системы.

What really is CPU Utilization?

aarti gupta

The metric we call CPU utilization is really “non-idle time”: the time the CPU was not running the idle thread. Your operating system kernel (whatever it is) usually tracks this during context switch. If a non-idle thread begins running, then stops 100 milliseconds later, the kernel considers that CPU utilized that entire time.

%CPU can be broken into two components

instruction-retired cycles and stalled cycles, eg, %INS and %STL.

It is wrong to interpret high %CPU to mean that the processing unit is the bottleneck.

With hyperthreads, however, those stalled cycles can now be used by another thread, so %CPU may count cycles as utilized that are in fact available.

CPU Utilization is often waiting on bus traffic (loading caches, loading ram, loading instructions, decoding instructions) only rarely is the CPU _doing_ useful work.

The context of what you are measuring depends if this is useful work or not. The initial access of a buffer almost universally stalls (unless you prefetched 100+ instructions ago). But starting to stream this data into L1 is useful work.

Aiming for 100%+ IPC is _beyond_ difficult even for simple algorithms and critical hot path functions. You not only require assembler cooperation (to assure decoder alignment), but you need to know _what_ processor you are running on to know the constraints of its decoder, uOP cache, and uOP cache alignment.

The idea here is that it appears that you are limited by the CPU and want to make things faster.

instructions/cycle (IPC)(note the total IPC = no of cores!)

Low level performance can be accurately measured using IPC, instructions per cycle. IPC shows on average how many instructions we were completed for each CPU clock cycle. The higher, the better (a simplification). The above example of 0.78 sounds not bad (78% busy?) until you realize that this processor’s top speed is an IPC of 4.0. This is also known as 4-wide, referring to the instruction fetch/decode path. Which means, the CPU can retire (complete) four instructions with every clock cycle.So an IPC of 0.78 on a 4-wide system, means the CPUs are running at 19.5% their top speed. Newer Intel processors may move to 5-wide.

If your IPC is < 1.0, you are likely memory stalled, and software tuning strategies include reducing memory I/O, and improving CPU caching and memory locality, especially on NUMA systems. Hardware tuning includes using processors with larger CPU caches, and faster memory, busses, and interconnects.

If your IPC is > 1.0, you are likely instruction bound. Look for ways to reduce code execution: eliminate unnecessary work, cache operations, etc. CPU flame graphs are a great tool for this investigation. For hardware tuning, try a faster clock rate, and more cores/hyperthreads.

When doing optimized code, the question “should I optimize for memory or for computing?” comes up often. Should I cache results? Should I use a more complex data structure in order to save memory or improve locality?

IPC is a good indicator on how you should tackle the problem. High IPC means you are may be doing too many calculations, while low IPC means that you should look at your memory usage. BTW, most of the time, memory is the problem.

Linux Load averages

Load average — is the average system load calculated over a given period of time of 1, 5 and 15 minutes.

You probably have a system with multiple CPUs or a multi-core CPU. The load average numbers work a bit differently on such a system. For example, if you have a load average of 2 on a single-CPU system, this means your system was overloaded by 100 percent — the entire period of time, one process was using the CPU while one other process was waiting. On a system with two CPUs, this would be complete usage — two different processes were using two different CPUs the entire time. On a system with four CPUs, this would be half usage — two processes were using two CPUs, while two CPUs were sitting idle.

To understand the load average number, you need to know how many CPUs your system has. A load average of 6.03 would indicate a system with a single CPU was massively overloaded, but it would be fine on a computer with 8 CPUs.

Deeper metrics

When Linux load averages increase, you know you have higher demand for resources (CPUs, disks, and some locks), but you aren’t sure which. You can use other metrics for clarification. For example, for CPUs:

  • per-CPU utilization: eg, using mpstat -P ALL 1
  • per-process CPU utilization: eg, top, pidstat 1, etc.
  • per-thread run queue (scheduler) latency: eg, in /proc/PID/schedstats, delaystats, perf sched
  • CPU run queue latency: eg, in /proc/schedstat, perf sched, my runqlatbcc tool.
  • CPU run queue length: eg, using vmstat 1 and the ‘r’ column, or my runqlen bcc tool.

The first two are utilization metrics, the last three are saturation metrics. Utilization metrics are useful for workload characterization, and saturation metrics useful for identifying a performance problem. The best CPU saturation metrics are measures of run queue (or scheduler) latency: the time a task/thread was in a runnable state, but had to wait its turn. These allow you to calculate the magnitude of a performance problem, eg, the percent of time a thread spent in scheduler latency. Measuring the run queue length instead can suggest that there is a problem, but it’s more difficult to estimate the magnitude

What is cpu utilization?

CPU time is the amount of time for which a central processing unit was used for processing instructions of a computer program or operating system, as opposed to elapsed time, which includes for example, waiting for input/output operations or entering low-power mode. The CPU time is measured in clock ticks or seconds.

What is a good CPU utilization?

How Much CPU Usage is Normal? Normal CPU usage is 2-4% at idle, 10% to 30% when playing less demanding games, up to 70% for more demanding ones, and up to 100% for rendering work. When watching YouTube it should be around 5% up to 15% (total), depending on your CPU, browser and video quality.

What do you mean by CPU utilization?

CPU utilization refers to a computer’s usage of processing resources, or the amount of work handled by a CPU. . Certain tasks require heavy CPU time, while others require less because of non-CPU resource requirements.

What increases CPU utilization?

The higher the performance of a CPU, the faster the PC will run. Depending on the applications you open, CPU may increase. . Instead, there may be too many CPU-intensive programs actively running at the same time and the CPU could have reached its usage limit.

Why is my CPU usage at 100%?

Malware or viruses on you PC may also cause the CPU 100% usage issue. So try running an antivirus scan to see if there are viruses, spywares or Trojans on your PC. If the antivirus software on your PC detected malware or virus, you need to delete them immediately.

Concept of CPU utilization | Memory management | Operating system

44 related questions found

How do I know if my CPU is overloaded?

Simply hover the mouse pointer over the Task Manager icon in the Systray or notification area and the status will pop up. In the Task Manager itself, click the Processes tab. Then click the CPU column heading to sort the processes by how much of the CPU they’re using. Whatever process is hogging the CPU will be on top.

How do I reduce my CPU usage at 100?

  1. Reboot. First step: save your work and restart your PC. .
  2. End or Restart Processes. Open the Task Manager (CTRL+SHIFT+ESCAPE). .
  3. Update Drivers. .
  4. Scan for Malware. .
  5. Power Options. .
  6. Find Specific Guidance Online. .
  7. Reinstalling Windows.

Why is CPU utilization important?

Consequently, CPU utilization becomes a very important metric to determine how well an application is using the cores. . Actual CPU utilization varies depending on the amount and type of managed computing tasks. Certain tasks require heavy CPU time, while others require less because of non-CPU resource requirements.

How do I check my CPU utilization?

  1. Press WIN + R on the keyboard to open the Run dialogue. Type resmon in the text box and press Enter to open the Resource Monitor.
  2. Click the CPU tab. .
  3. Click the Average CPU column header to sort by overall CPU usage.

Why is CPU utilization high in server?

High CPU usage because of storage performance issues. Storage performance issues can cause high CPU usage on SMB servers. . In most cases, you will notice the issue of high CPU usage in the system process.

What is CPU utilization in Oracle?

Oracle CPU Utilization. . V$SESSTAT shows Oracle CPU usage per session. You can use this view to determine which particular session is using the most CPU. V$RSRC_CONSUMER_GROUP shows CPU utilization statistics on a per consumer group basis, if you are running the Oracle Database Resource Manager.

What is CPU utilization in AWS?

CPU utilization is the percentage of allocated EC2 compute units that are currently in use on the instance. This metric measures the percentage of allocated CPU cycles that are being utilized on an instance. The CPU Utilization CloudWatch metric shows CPU usage per instance and not CPU usage per core.

What is normal CPU temp?

The CPU temp depends entirely on the CPU used. In general, anything between 40°C and 65°C (or 104°F — 149°F) is considered a safe heat range during a normal workload.

Is 50 CPU usage bad?

Reputable. It’s perfectly fine. Your cpu only works as hard as it needs to so it saves power. You’ve got a good cpu so it chills when gaming.

What CPU usage is good for gaming?

The best CPU usage would most likely be around 80-80% max. This means you are utilizing more of your CPU’s capabilities while giving it some leeway to handle a spike in CPU usage.

How do I check my CPU and memory utilization in Windows?

  1. Press the Windows key , type task manager, and press Enter .
  2. In the window that appears, click the Performance tab.
  3. On the Performance tab, a list of hardware devices is displayed on the left side.

What is the difference between CPU usage and CPU utilization?

cpu. utilization — Provides statistics for physical CPUs. . usage — Provides statistics for logical CPUs. This is based on CPU Hyperthreading.

What affects CPU usage?

The causes of high CPU usage are wide-ranging—and in some cases, surprising. Slower processing speeds could easily be the result of either the antivirus program you are running, or a virus that the software was designed to stop. . Try either scanning with multiple antivirus tools or performing a manual virus removal.

What is RAM utilization?

1. The amount of RAM used by a particular system at a certain unit of time. Learn more in: A Study of Contemporary System Performance Testing Framework. Refers to the amount of main memory used during software execution.

Can low RAM cause high CPU usage?

So yes, low memory can cause higher CPU usage. The problem is that very low memory can cause memory starvation to the point that the system is paging in and out so much data that disk input and output times dominate over everything else.

Why is my computer so slow?

A slow computer is often caused by too many programs running simultaneously, taking up processing power and reducing the PC’s performance. . Click the CPU, Memory, and Disk headers to sort the programs that are running on your computer by how much of your computer’s resources they are taking.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *