Linux

Загрузка CPU по ядрам

Считает использование CPU и iowait по /proc/stat, показывает частоты и температуры.

Python Linux Средний
Скачать cpu_usage.py
Описание

Что делает скрипт

Скрипт снимает два образца /proc/stat с заданным интервалом и вычисляет общую и поядерную загрузку, включая user, system и iowait. Дополнительно читаются governor, текущая частота и тепловые зоны из sysfs. Отчёт можно сохранить в JSON, настройки ядра не меняются.

Запуск

Быстрый старт

python cpu_usage.py --interval 1

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python cpu_usage.py
  • python cpu_usage.py --interval 2 --per-core
  • python cpu_usage.py --json cpu.json
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Linux sudo apt install python3
Исходник

cpu_usage.py

#!/usr/bin/env python3
"""Загрузка CPU по ядрам из /proc/stat."""
from __future__ import annotations

import argparse
import json
import time
from dataclasses import asdict, dataclass
from pathlib import Path

FIELDS = ("user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal")


@dataclass
class CoreUsage:
    core: str
    usage: float
    user: float
    system: float
    iowait: float
    idle: float


def read_stat() -> dict[str, list[int]]:
    rows: dict[str, list[int]] = {}
    for line in Path("/proc/stat").read_text(encoding="utf-8").splitlines():
        if not line.startswith("cpu"):
            continue
        parts = line.split()
        values = [int(item) for item in parts[1:9]]
        while len(values) < 8:
            values.append(0)
        rows[parts[0]] = values
    return rows


def compute(previous: list[int], current: list[int]) -> CoreUsage:
    deltas = [max(current[index] - previous[index], 0) for index in range(8)]
    total = sum(deltas)
    if total == 0:
        return CoreUsage("unknown", 0.0, 0.0, 0.0, 0.0, 0.0)
    idle = deltas[3] + deltas[4]
    return CoreUsage("", (total - idle) / total * 100, deltas[0] / total * 100, (deltas[2] + deltas[5] + deltas[6]) / total * 100, deltas[4] / total * 100, deltas[3] / total * 100)


def cpu_model() -> str:
    for line in Path("/proc/cpuinfo").read_text(encoding="utf-8", errors="replace").splitlines():
        if line.lower().startswith("model name"):
            return line.split(":", 1)[1].strip()
    return "неизвестно"


def frequencies() -> list[str]:
    result = []
    for path in sorted(Path("/sys/devices/system/cpu").glob("cpu[0-9]*/cpufreq/scaling_cur_freq")):
        try:
            value = int(path.read_text(encoding="utf-8").strip()) // 1000
            result.append(f"{path.parent.parent.name}: {value} MHz")
        except (OSError, ValueError):
            continue
    return result


def governors() -> list[str]:
    values = set()
    for path in Path("/sys/devices/system/cpu").glob("cpu[0-9]*/cpufreq/scaling_governor"):
        try:
            values.add(path.read_text(encoding="utf-8").strip())
        except OSError:
            continue
    return sorted(values)


def temperatures() -> list[str]:
    result = []
    for path in sorted(Path("/sys/class/thermal").glob("thermal_zone*")):
        try:
            zone_type = (path / "type").read_text(encoding="utf-8").strip()
            raw = int((path / "temp").read_text(encoding="utf-8").strip())
            result.append(f"{zone_type}: {raw / 1000:.1f} C")
        except (OSError, ValueError):
            continue
    return result


def main() -> int:
    parser = argparse.ArgumentParser(description="Загрузка CPU Linux")
    parser.add_argument("--interval", type=float, default=1.0, help="Интервал измерения в секундах")
    parser.add_argument("--per-core", action="store_true", help="Показать только ядра")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
    args = parser.parse_args()

    if args.interval < 0.1:
        parser.error("--interval должен быть не меньше 0.1")

    first = read_stat()
    time.sleep(args.interval)
    second = read_stat()

    common = sorted(set(first).intersection(second), key=lambda value: (value != "cpu", int(value[3:]) if value[3:].isdigit() else 0))
    rows: list[CoreUsage] = []
    for key in common:
        item = compute(first[key], second[key])
        item.core = key
        rows.append(item)

    aggregate = next((item for item in rows if item.core == "cpu"), None)
    if aggregate and not args.per_core:
        print(f"CPU: {cpu_model()}")
        print(f"Общая загрузка: {aggregate.usage:.1f}%")
        print(f"user {aggregate.user:.1f}%, system {aggregate.system:.1f}%, iowait {aggregate.iowait:.1f}%, idle {aggregate.idle:.1f}%")
        gov = ", ".join(governors()) or "нет данных"
        print(f"Governor: {gov}")
        freqs = frequencies()
        if freqs:
            print("Частоты: " + ", ".join(freqs[:8]))
        temps = temperatures()
        if temps:
            print("Температуры: " + ", ".join(temps[:8]))
        print()

    print(f"{'ЯДРО':<8} {'ЗАГРУЗКА':>9} {'USER':>7} {'SYSTEM':>8} {'IOWAIT':>7} {'IDLE':>7}")
    print("-" * 54)
    for item in rows:
        if item.core == "cpu" and args.per_core:
            continue
        print(f"{item.core:<8} {item.usage:>8.1f}% {item.user:>6.1f}% {item.system:>7.1f}% {item.iowait:>6.1f}% {item.idle:>6.1f}%")

    if args.json:
        args.json.write_text(
            json.dumps(
                {
                    "model": cpu_model(),
                    "governors": governors(),
                    "frequencies": frequencies(),
                    "temperatures": temperatures(),
                    "cores": [asdict(item) for item in rows],
                },
                ensure_ascii=False,
                indent=2,
            )
            + "\n",
            encoding="utf-8",
        )
        print(f"\nJSON сохранён: {args.json}")

    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get linux-cpu-usage
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Linux

Bash и Python для серверов, рабочих станций и повседневных задач Linux.