How to Find the Process That Is Overloading the CPU
Use ps and top for quick CPU diagnostics: compare snapshots with current activity, account for multiple cores, and do not stop processes at random.

In this article
Сайт стал отвечать медленно, а график процессора вырос. Нужно определить, кто выполняет работу и совпадает ли она по времени с задержками. Самый заметный процесс в одном снимке не обязательно является причиной: он мог активно работать раньше или выполнять полезное фоновое задание.
Получите список кандидатов
Примеры предназначены для Linux с procps. Команда ниже показывает процессы, сортируя их по доле CPU:
ps -eo pid,ppid,user,stat,pcpu,pmem,comm --sort=-pcpu
В выводе есть идентификатор процесса, родитель, пользователь, состояние и короткое имя команды. Мы намеренно не выводим полную командную строку: в её аргументах иногда оказываются секреты. Если список передаётся в поддержку, проверьте его на чувствительные имена пользователей и приложений.
У ps доля CPU рассчитывается за время жизни процесса. Она удобна для отбора, но не заменяет наблюдение за последними секундами. Долго работающий сервис с недавним всплеском может не оказаться на первом месте.
Сравните несколько интервалов
Для краткого наблюдения можно получить три пакетных снимка top:
top -b -d 2 -n 3
Интервал между обновлениями составляет две секунды. Вывод может быть длинным, поэтому смотрите на повторяющиеся процессы и общую картину CPU, а не только на первую строку. Первый снимок не используйте как единственное доказательство текущей нагрузки.
На многоядерной системе процесс может показывать больше ста процентов в принятом top режиме подсчёта. Это не обязательно ошибка измерения: несколько потоков используют несколько логических процессоров. Важны доступные ресурсы и настройки отображения.
Разделите вычисления и ожидание
Если один рабочий процесс постоянно занимает CPU, нужно связать его с задачей: обработкой запросов, импортом, сжатием или другой операцией. Если нагрузка распределена между множеством однотипных процессов, посмотрите, не выросло ли число одновременных обращений.
Низкая загрузка CPU при медленном сайте не снимает проблему. Приложение может ждать базу данных, диск или внешний сервис. Высокая средняя нагрузка системы также не равна проценту занятости процессора: это другой показатель.
Проверьте рабочий контекст
Пример: во время загрузки каталога процесс импорта находится вверху списка. Если после завершения задачи время ответа возвращается к обычному, связь вероятна, но ещё полезно проверить расписание и ресурсы импорта. Если же задержки продолжаются при исчезновении процесса, причина может быть другой.
Идентификаторы процессов переиспользуются. Не сохраняйте номер для отложенного вмешательства без повторной проверки владельца и назначения. Завершать найденный процесс по одному снимку нельзя: он может проводить важную операцию или автоматически запускаться заново.
Результат короткой диагностики
Запишите время, команду, пользователя, устойчивость нагрузки и действие, которое выполнялось на сайте. После исправления сравните те же показатели при похожем потоке запросов. Цель — установить, какой сценарий потребляет CPU и влияет ли он на пользователей, а затем выбрать изменение, результат которого можно измерить.
The site has become slow, and the CPU usage graph has risen. You need to identify which process is doing the work and whether its activity aligns with the delays. The most prominent process in a single snapshot is not necessarily the cause: it might have been active earlier or performing a useful background task.
Get a list of candidates
Examples are for Linux with procps. The command below lists processes sorted by CPU usage:
ps -eo pid,ppid,user,stat,pcpu,pmem,comm --sort=-pcpu
The output includes the process ID, parent process, user, state, and a short command name. We intentionally omit the full command line: its arguments sometimes contain secrets. If the list is sent to support, check it for sensitive user and application names.
The CPU share for ps is calculated over the process lifetime. This is useful for filtering but does not replace monitoring the last few seconds. A long-running service with a recent spike may not appear at the top.
Compare multiple intervals
For brief observation, you can obtain three batch snapshots top:
top -b -d 2 -n 3
The update interval is two seconds. The output can be long, so look for recurring processes and the overall CPU picture, not just the first line. Do not use the first snapshot as the sole evidence of current load.
On a multi-core system, a process may show more than one hundred percent in the accepted top counting mode. This is not necessarily a measurement error: multiple threads use multiple logical processors. Available resources and display settings are what matter.
Separate computation from waiting
If a single worker process constantly consumes CPU, link it to a task: request handling, import, compression, or another operation. If the load is distributed among many identical processes, check whether the number of concurrent requests has increased.
Low CPU usage on a slow site does not rule out the problem. The application may be waiting for a database, disk, or external service. High average system load is also not equivalent to CPU utilization percentage; these are different metrics.
Check the working context
Example: during catalog loading, the import process appears at the top of the list. If response time returns to normal after the task completes, a link is likely, but it is still useful to check the import schedule and resources. If delays persist after the process disappears, the cause may be different.
Process identifiers are reused. Do not save a number for deferred intervention without rechecking the owner and purpose. Terminating a found process based on a single snapshot is not allowed: it may be performing an important operation or automatically restarting.
Result of short diagnostics
Record the time, command, user, load stability, and the action performed on the site. After the fix, compare the same metrics under a similar request flow. The goal is to identify which scenario consumes CPU and whether it affects users, then select a change with measurable results.





Discussion 0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.