Linux 系統性能優化高級全流程指南
一、系統基礎狀態捕獲
1. 系統信息建檔
除了原有的硬件、內核和存儲拓撲信息收集,還增加 CPU 緩存、網絡設備詳細信息等。
# 硬件信息
lscpu > /opt/tuning/lscpu.origin
dmidecode -t memory > /opt/tuning/meminfo.origin
lspci -vvv > /opt/tuning/pci.origin
getconf -a | grep CACHE > /opt/tuning/cache_info.origin # 獲取 CPU 緩存信息# 內核信息
uname -a > /opt/tuning/kernel.origin
sysctl -a > /opt/tuning/sysctl.origin# 存儲拓撲
lsblk -O > /opt/tuning/lsblk.origin
nvme list > /opt/tuning/nvme.origin# 網絡設備信息
ethtool eth0 > /opt/tuning/eth0_info.origin # 假設網卡為 eth0
2. 性能基線測試
增加更多維度的性能測試,如 CPU 多核性能、內存帶寬測試等。
# CPU 單核性能(計算素數)
sysbench cpu --cpu-max-prime=20000 run | tee /opt/tuning/cpu_origin.log# CPU 多核性能
sysbench cpu --cpu-max-prime=20000 --threads=$(nproc) run | tee /opt/tuning/cpu_multi_origin.log# 內存延遲測試
sudo apt-get install lmbench -y
lat_mem_rd 1G 512 | tee /opt/tuning/mem_latency.origin# 內存帶寬測試
stream | tee /opt/tuning/mem_bandwidth.origin# 磁盤隨機 IOPS(混合讀寫)
fio --name=baseline --rw=randrw --bs=4k --direct=1 --runtime=60 \
--iodepth=64 --ioengine=libaio --group_reporting | tee /opt/tuning/fio_origin.log# 網絡基礎吞吐
iperf3 -c 10.0.0.2 -t 30 -P 8 | tee /opt/tuning/iperf_origin.log
二、分項優化與驗證
1. 內核參數調優
除了原有的 TCP 相關參數,調整更多內核參數以優化系統整體性能。
# 原始狀態捕獲
sysctl -n net.ipv4.tcp_tw_reuse
sysctl -n net.ipv4.tcp_fin_timeout
sysctl -n vm.swappiness
ss -s | grep TIMEWAIT# 優化操作
echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
echo "net.ipv4.tcp_fin_timeout = 15" >> /etc/sysctl.conf
echo "vm.swappiness = 10" >> /etc/sysctl.conf
sysctl -p# 驗證測試
wrk -t12 -c4000 -d60s http://target:8080
watch -n1 "ss -s | grep TIMEWAIT"
vmstat 1 10 # 觀察交換情況
2. 文件系統優化
除了修改掛載參數,還可以根據文件系統類型進行針對性優化。
# 原始測試
mount | grep " / " > /opt/tuning/mount.origin
fio --name=testfs --directory=/mnt/data --rw=randwrite \
--bs=4k --numjobs=16 --time_based --runtime=300 \
--group_reporting | tee /opt/tuning/fio_fs_origin.log# 優化操作
if grep -q ext4 /etc/fstab; thentune2fs -o journal_data_writeback /dev/sda1 # 假設掛載在 /dev/sda1
fi
vim /etc/fstab
# 修改為:noatime,nodiratime,data=writeback,barrier=0
umount /mnt/data && mount -a# 驗證測試
fio --name=testfs_tuned --directory=/mnt/data --rw=randwrite \
--bs=4k --numjobs=16 --time_based --runtime=300 \
--group_reporting | tee /opt/tuning/fio_fs_tuned.log
diff -y <(awk '/IOPS/' fio_fs_origin.log) <(awk '/IOPS/' fio_fs_tuned.log)
3. 網絡棧優化
除了調整 TCP 參數,還可以優化網絡設備隊列和中斷綁定。
# 原始抓包分析
tcpdump -i eth0 -w tcp_handshake.pcap 'tcp port 80 and tcp[tcpflags] & (tcp-syn|tcp-ack) == tcp-syn'
tshark -r tcp_handshake.pcap -T fields -e tcp.time_delta | sort -n > tcp_delay.origin# 優化操作
echo "net.ipv4.tcp_slow_start_after_idle = 0" >> /etc/sysctl.conf
echo "net.ipv4.tcp_adv_win_scale = 1" >> /etc/sysctl.conf
ethtool -L eth0 combined $(nproc) # 調整網卡隊列數
for i in $(ls /sys/class/net/eth0/queues/rx-*/rps_cpus); do echo ffff > $i; done # 配置 RPS
sysctl -p# 驗證測試
ab -n 100000 -c 500 -k http://target:8080/ | tee /opt/tuning/ab_tuned.log
awk '/Requests per second/ {print $4}' ab_origin.log ab_tuned.log | \
gnuplot -p -e 'plot "-" using 0:1 with lines title "QPS"; pause -1'
三、自動化對比腳本
完善自動化對比腳本,增加更多性能指標的對比。
#!/bin/bash
# perf_compare.shBEFORE_LOG=$1
AFTER_LOG=$2# CPU 性能對比
before_cpu=$(grep "events per second" $BEFORE_LOG/cpu_origin.log | awk '{print $4}')
after_cpu=$(grep "events per second" $AFTER_LOG/cpu_origin.log | awk '{print $4}')
cpu_gain=$(echo "scale=2; ($after_cpu - $before_cpu)/$before_cpu*100" | bc)before_cpu_multi=$(grep "events per second" $BEFORE_LOG/cpu_multi_origin.log | awk '{print $4}')
after_cpu_multi=$(grep "events per second" $AFTER_LOG/cpu_multi_origin.log | awk '{print $4}')
cpu_multi_gain=$(echo "scale=2; ($after_cpu_multi - $before_cpu_multi)/$before_cpu_multi*100" | bc)# 內存延遲對比
before_mem=$(grep "0.00625" $BEFORE_LOG/mem_latency.origin | awk '{print $2}')
after_mem=$(grep "0.00625" $AFTER_LOG/mem_latency.origin | awk '{print $2}')# 內存帶寬對比
before_mem_bw=$(grep "Copy" $BEFORE_LOG/mem_bandwidth.origin | awk '{print $2}')
after_mem_bw=$(grep "Copy" $AFTER_LOG/mem_bandwidth.origin | awk '{print $2}')
mem_bw_gain=$(echo "scale=2; ($after_mem_bw - $before_mem_bw)/$before_mem_bw*100" | bc)# 生成報告
cat << EOF
[性能對比報告]
CPU 單核計算能力提升: ${cpu_gain}%
CPU 多核計算能力提升: ${cpu_multi_gain}%
內存訪問延遲變化: ${before_mem}ns -> ${after_mem}ns
內存帶寬提升: ${mem_bw_gain}%磁盤隨機寫 IOPS:
- 優化前: $(grep write $BEFORE_LOG/fio_origin.log | cut -d= -f2)
- 優化后: $(grep write $AFTER_LOG/fio_origin.log | cut -d= -f2)網絡吞吐量提升:
$(paste $BEFORE_LOG/iperf_origin.log $AFTER_LOG/iperf_origin.log | column -t)
EOF
四、可視化分析方法
1. 使用 gnuplot 繪制性能對比
除了 CPU 使用率對比,增加內存使用率、磁盤 I/O 等對比。
# CPU 使用率對比(sar 數據)
sar -f sar_origin.log -u | awk 'NR>3 {print $1,$3+$5}' > cpu_origin.dat
sar -f sar_tuned.log -u | awk 'NR>3 {print $1,$3+$5}' > cpu_tuned.dat# 內存使用率對比
sar -f sar_origin.log -r | awk 'NR>3 {print $1,$4}' > mem_origin.dat
sar -f sar_tuned.log -r | awk 'NR>3 {print $1,$4}' > mem_tuned.dat# 磁盤 I/O 對比
sar -f sar_origin.log -d | awk 'NR>3 {print $1,$3}' > disk_origin.dat
sar -f sar_tuned.log -d | awk 'NR>3 {print $1,$3}' > disk_tuned.datgnuplot -persist << EOF
set multiplot layout 3,1
set title "CPU Utilization Comparison"
set xlabel "Time"
set ylabel "Usage %"
plot "cpu_origin.dat" with lines title "Original", \"cpu_tuned.dat" with lines title "Tuned"set title "Memory Utilization Comparison"
set xlabel "Time"
set ylabel "Usage %"
plot "mem_origin.dat" with lines title "Original", \"mem_tuned.dat" with lines title "Tuned"set title "Disk I/O Comparison"
set xlabel "Time"
set ylabel "IOPS"
plot "disk_origin.dat" with lines title "Original", \"disk_tuned.dat" with lines title "Tuned"
unset multiplot
EOF
2. 火焰圖對比分析
增加更多維度的火焰圖分析,如內存分配、I/O 操作等。
# 采集優化前數據
perf record -F 99 -ag -- sleep 30
mv perf.data perf.origin.data
perf record -e mem-stores -F 99 -ag -- sleep 30
mv perf.data perf.mem.origin.data
perf record -e block:block_rq_issue -F 99 -ag -- sleep 30
mv perf.data perf.io.origin.data# 采集優化后數據
perf record -F 99 -ag -- sleep 30
mv perf.data perf.tuned.data
perf record -e mem-stores -F 99 -ag -- sleep 30
mv perf.data perf.mem.tuned.data
perf record -e block:block_rq_issue -F 99 -ag -- sleep 30
mv perf.data perf.io.tuned.data# 生成對比視圖
difffolded.pl perf.origin.data perf.tuned.data | flamegraph.pl > diff.svg
difffolded.pl perf.mem.origin.data perf.mem.tuned.data | flamegraph.pl > diff_mem.svg
difffolded.pl perf.io.origin.data perf.io.tuned.data | flamegraph.pl > diff_io.svg
五、深度監控指標
1. 實時監控看板
使用 Grafana 和 Prometheus 搭建更強大的監控系統。
# 安裝 Prometheus 和 Grafana
sudo apt-get install prometheus grafana -y# 配置 Prometheus 監控節點
vim /etc/prometheus/prometheus.yml
# 添加以下內容
scrape_configs:- job_name: 'node'static_configs:- targets: ['localhost:9100']# 啟動 Prometheus 和 Grafana
sudo systemctl start prometheus grafana-server
sudo systemctl enable prometheus grafana-server# 導入 Grafana 儀表盤模板
# 訪問 http://localhost:3000,添加 Prometheus 數據源,導入預定義的儀表盤模板
2. 關鍵性能指標告警
完善 Prometheus 告警規則,增加更多告警指標。
# 使用 prometheus 配置規則
groups:
- name: Tuning Alertsrules:- alert: HighContextSwitchexpr: rate(process_stat_context_switches_total[5m]) > 100000for: 10mannotations:description: '上下文切換過高:{{ $value }}次/秒'- alert: HighMemoryUsageexpr: node_memory_MemUsed / node_memory_MemTotal * 100 > 90for: 10mannotations:description: '內存使用率過高:{{ $value }}%'- alert: HighDiskUsageexpr: (node_filesystem_size_bytes{mountpoint="/"} - node_filesystem_free_bytes{mountpoint="/"}) / node_filesystem_size_bytes{mountpoint="/"} * 100 > 90for: 10mannotations:description: '磁盤使用率過高:{{ $value }}%'
六、優化回滾機制
1. 內核參數回滾
# 備份原始配置
cp /etc/sysctl.conf /etc/sysctl.conf.bak_$(date +%s)# 快速回滾命令
sysctl -p /etc/sysctl.conf.bak
2. 文件系統回滾
# 使用 btrfs 快照
btrfs subvolume list /
btrfs subvolume set-default <原快照 ID> /
reboot
3. 網絡棧配置回滾
# 備份網絡配置
cp /etc/sysctl.conf /etc/sysctl.conf.net_bak_$(date +%s)
cp /etc/network/interfaces /etc/network/interfaces.bak_$(date +%s)# 回滾網絡配置
sysctl -p /etc/sysctl.conf.net_bak
cp /etc/network/interfaces.bak /etc/network/interfaces
reboot
通過以上更全面、更深入的優化方案,可以更細致地對 Linux 系統進行性能優化,并實時監控優化效果,確保系統始終處于最佳運行狀態。