3 статьи

  1. https://www.brendangregg.com/blog/2017-08-08/linux-load-averages.html
  2. https://www.baeldung.com/linux/total-process-cpu-usage
  3. proccess status

Начнём с первой… это прям настоящий детектив. Особенно на фразе

“I searched over 6,000 digests containing over 98,000 emails, 30,000 of which were from 1993”

Тут я напишу основные тезисы которые я вынес из этой статьи…

Если просто:

The original load averages show only CPU demand: the number of processes running plus those waiting to run. There’s a nice description of this in RFC 546 titled “TENEX Load Averages”, August 1973:

[1] The TENEX load average is a measure of CPU demand. The load average is an average of the number of runnable processes over a given time period. For example, an hourly load average of 10 would mean that (for a single CPU system) at any time during that hour one could expect to see 1 process running and 9 others ready to run (i.e., not blocked for I/O) waiting for the CPU.

Он как бы нам говорит что оригинальный load averages показывал только нагрузку CPU, т.е количество запущенных процессов+ожидающих запуска(only ‘R’ = RUNNING & RUNNABLE).

Как известно LA

Как известно LA у нас по умолчанию показывает значения средней нагрузки за 1, 5, 15 минут. На самом деле 1, 5, 15 это лишь константы которые захардкоженны в уравнение вычисления средней нагрузки (странно если бы было подругому…) про уравнения соответственно тут В качестве подтверждения предлагается забацать тест который на системе с нагрузкой 0 запустит чё нить типа:

1
while true; do true; done

Через минуту поидее наше LA не вырастет до 1. А будет где то в районе 0.6

В linux в LA добавили процессы uninterruptible sleep “D”.

Подробнее о них можно почитать тут. Т.е был найден комментарий 1993 года к патчу в ядро который выглядит так:

From: Matthias Urlichs urlichs@smurf.sub.org
Subject: Load average broken ?
Date: Fri, 29 Oct 1993 11:37:23 +0200
The kernel only counts “runnable” processes when computing the load average. I don’t like that; the problem is that processes which are swapping or waiting on “fast”, i.e. noninterruptible, I/O, also consume resources. It seems somewhat nonintuitive that the load average goes down when you replace your fast swap disk with a slow swap disk… Anyway, the following patch seems to make the load average much more consistent WRT the subjective speed of the system. And, most important, the load is still zero when nobody is doing anything. ;-)

Т.е в 1993 году таки был запилен патч который говорил что дескать интерпритировать LA только по процессам “R” это не показательно поэтому были добавлены еще “D” процессы. (еще раз про процессы и их статусы тут)

Спустя 20+ лет ядро поменялось и теперь

“Nowadays, in Linux 4.12, there are nearly 400 codepaths that set TASK_UNINTERRUPTIBLE, including some lock primitives.”
“The use of the uninterruptible state has since grown in the Linux kernel, and nowadays includes uninterruptible lock primitives”

Так что не очень понятно правильно ли мы вообще считаем теперь LA. Вообщем то однозначного ответа на вопрос нет. И смотреть на LA предлагается исключительно с точки зрения 3х значений т.е.

  • Если LA 0 значит ни фига не происходит
  • Если LA за 1 min больше чем за 5 или 15 значит нагрузка увеличивается
  • Если LA за 1 min меньше чем за 5 или 15 значит нагрузка уменьшается
  • Если LA больше чем количество CPU значит потенциально у нас проблемы с производительностью

В качестве диагностики предлагается использовать более передовые инструменты:

  • 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 runqlat bcc tool.
  • CPU run queue length: eg, using vmstat 1 and the ‘r’ column, or my runqlen bcc tool.

P.S Настоятельно рекомендую прочитать оригиналы… Серега говорил htop круто… подтверждаю.

процессы и их статусы… Вообщем то всё видно в таблице в man ps

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#--------------------------------------------------
PROCESS STATE CODES         top
       Here are the different values that the s, stat and state output
       specifiers (header "STAT" or "S") will display to describe the
       state of a process:

               D    uninterruptible sleep (usually IO)
               I    Idle kernel thread
               R    running or runnable (on run queue)
               S    interruptible sleep (waiting for an event to
                    complete)
               T    stopped by job control signal
               t    stopped by debugger during the tracing
               W    paging (not valid since the 2.6.xx kernel)
               X    dead (should never be seen)
               Z    defunct ("zombie") process, terminated but not
                    reaped by its parent

       For BSD formats and when the stat keyword is used, additional
       characters may be displayed:

               <    high-priority (not nice to other users)
               N    low-priority (nice to other users)
               L    has pages locked into memory (for real-time and
                    custom IO)
               s    is a session leader
               l    is multi-threaded (using CLONE_THREAD, like NPTL
                    pthreads do)
               +    is in the foreground process group
#-------------------------------------------------------------------------

Не стыдная комманда из того же man

1
ps -eo pid,ppid,tid,class,rtprio,ni,pri,psr,pcpu,stat,wchan:14,comm