温馨提示×

Linux CPUInfo:CPU主频怎样优化

小樊
43
2025-12-26 20:06:16
栏目: 智能运维

Linux CPU主频优化指南

一 核心思路与前提检查

  • 明确目标:追求低延迟/稳定高频优先选用performance;追求功耗/温度优先选用powersave;通用场景可用ondemand/conservative/schedutil。现代内核的schedutil(自Linux 4.7)依据调度器利用率调频,响应更自然;而intel_pstate驱动在现代 Intel CPU 上优先启用,仅提供performance/powersave两档,若需使用其他 governor 可在内核参数中禁用该驱动。
  • 检查驱动与当前策略:
    • 查看是否加载 acpi_cpufreqlsmod | grep acpi_cpufreq
    • 查看可用策略与当前策略:cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governorscat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
    • 查看频率信息:cat /proc/cpuinfo | grep -i "cpu mhz";更建议使用 cpupower frequency-info 获取详细与当前频率。

二 快速优化步骤

  • 临时切换到高性能:
    • 通用工具:sudo cpupower -c all frequency-set -g performance
    • 直接写入 sysfs:echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
  • 持久化设置:
    • RHEL/CentOS 7/8/9:sudo yum install -y kernel-tools,在 /etc/sysconfig/cpupower 中设置 CPUPOWER_START_OPTS="frequency-set -g performance",并启用服务 sudo systemctl enable --now cpupower.service
    • Debian/Ubuntu:sudo apt install -y cpufrequtils,编辑 /etc/default/cpufrequtils 设置 GOVERNOR="performance",重启服务 sudo systemctl restart cpufrequtils
    • 通用 systemd 单元(适用于所有发行版):创建 /etc/systemd/system/cpu-performance.service,内容示例:
      [Unit]
      Description=Set CPU governor to performance
      After=multi-user.target
      [Service]
      Type=oneshot
      ExecStart=/bin/bash -c 'for f in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do echo performance > "$f"; done'
      RemainAfterExit=yes
      [Install]
      WantedBy=multi-user.target
      
      启用:sudo systemctl daemon-reload && sudo systemctl enable --now cpu-performance.service
  • 验证:cpupower frequency-infocat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 应显示为 performance

三 进阶优化与稳定性

  • 放宽频率上下限(仅在需要时):
    • 查看可用频率:cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
    • 设置上限:echo <频率值kHz> | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq
    • 设置下限:echo <频率值kHz> | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_min_freq
  • 使用 userspace 固定频率(需先切到 userspace governor):
    • echo userspace | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
    • echo <频率值kHz> | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_setspeed
  • 避免冲突:部分系统存在 cpuspeed 等服务会与手动设置冲突,必要时停止:sudo systemctl stop cpuspeed(或 service cpuspeed stop)。

四 监控与 BIOS 层优化

  • 实时监控:
    • 综合信息:lscpu
    • 睿频/实际频率与功耗:turbostat
    • 性能剖析:perf stat(关注 CPI、指令吞吐等)
  • BIOS/UEFI 建议:在固件中启用High Performance/Max Performance,并视情况关闭 C-state 节能以稳定高频;注意这会增加功耗与温度,需确保散热与供电充足。

五 常见问题与排查

  • governor 不可用或被覆盖:确认驱动加载(lsmod | grep acpi_cpufreq),现代 Intel 平台可能使用 intel_pstate(仅 performance/powersave)。如需使用其他 governor,可在 /etc/default/grubGRUB_CMDLINE_LINUX_DEFAULT 添加 intel_pstate=disable 后更新 grub 并重启。
  • 频率不一致或波动异常:检查是否与其他调频服务冲突(如 cpuspeed),必要时停用;使用 turbostat 观察实际频率与 Tau(睿频时间)变化。
  • 设置未持久化:确认已通过发行版工具或 systemd 单元写入开机流程,并在重启后复核 scaling_governor

0