+
+
+
+
+
+
composer
+
meteor
+
+
+
+
+
+
+
+
+
+
+
+
supabase
raspbian
clion
+
+
+
redhat
vue
+
+
+
mocha
actix
===
+
koa
numpy
+
+
+
crystal
+
@
+
+
elementary
asm
+
chef
+
prometheus
+
+
+
+
?
+
+
rails
+
istio
ractive
dns
+
phpstorm
+
+
cdn
numpy
pascal
+
nim
+
sqlite
puppet
babel
+
+
+
+
wsl
actix
prettier
+
vscode
+
+
+
Back to Blog
⚡ Tuning CPU Performance: Simple Guide
Alpine Linux Performance CPU

⚡ Tuning CPU Performance: Simple Guide

Published Jun 4, 2025

Easy tutorial for beginners to tune CPU performance on Alpine Linux. Perfect for system optimization with step-by-step instructions and clear examples.

10 min read
0 views
Table of Contents

⚡ Tuning CPU Performance: Simple Guide

Let’s tune CPU performance on your Alpine Linux system! 🚀 This guide uses easy steps and simple words. We’ll make your processor work at its absolute best! 😊

🤔 What is CPU Performance Tuning?

CPU performance tuning is like training your computer’s brain to work faster and smarter!

Think of CPU tuning like:

  • 📝 Adjusting a race car’s engine for maximum speed and efficiency
  • 🔧 Organizing a chef’s kitchen for faster meal preparation
  • 💡 Optimizing a worker’s schedule to get more done in less time

🎯 What You Need

Before we start, you need:

  • ✅ Alpine Linux system running
  • ✅ Root access or sudo permissions
  • ✅ Basic understanding of system performance concepts
  • ✅ CPU monitoring tools for measuring improvements

📋 Step 1: Analyze Current CPU Performance

Check CPU Information and Usage

First, let’s see what we’re working with! 😊

What we’re doing: Gathering detailed information about your CPU and current performance to establish a baseline before optimization.

# Update package lists and install performance tools
apk update
apk add htop sysstat stress-ng cpufrequtils util-linux

# Check CPU information
lscpu
cat /proc/cpuinfo | head -30

# Check current CPU frequency and scaling
cpufreq-info 2>/dev/null || echo "cpufreq-info not available"
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor 2>/dev/null || echo "CPU frequency scaling not available"

# Check current CPU usage
top -bn1 | head -10
htop -d 1 -n 3

# Check CPU load averages
uptime
cat /proc/loadavg

# Monitor CPU statistics
iostat -c 1 5

# Check CPU interrupts and context switches
vmstat 1 5

# Check CPU cache information
getconf -a | grep CACHE

# Check NUMA topology (if available)
numactl --hardware 2>/dev/null || echo "NUMA not available"

What this does: 📖 Gives you a complete picture of your CPU capabilities and current performance.

Example output:

Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              4
Model name:          Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
CPU MHz:             1800.000
CPU max MHz:         3400.0000
CPU min MHz:         400.0000
Cache sizes:         L1d: 32K, L1i: 32K, L2: 256K, L3: 6144K

%Cpu(s):  5.2 us,  2.1 sy,  0.0 ni, 92.4 id,  0.3 wa,  0.0 hi,  0.0 si,  0.0 st
Load average: 0.42, 0.38, 0.35

What this means: You now know your CPU’s specifications and current workload! ✅

💡 Important Tips

Tip: Always measure performance before and after changes! 💡

Warning: CPU overclocking can cause system instability if done incorrectly! ⚠️

🛠️ Step 2: Configure CPU Frequency Scaling

Optimize CPU Governor Settings

Now let’s configure your CPU to scale efficiently! 😊

What we’re doing: Setting up CPU frequency scaling to balance performance and power consumption based on workload demands.

# Check available CPU governors
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors

# Check current governor for all CPUs
for cpu in /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor; do
    echo "$cpu: $(cat $cpu 2>/dev/null || echo 'Not available')"
done

# Set performance governor for maximum speed
echo "performance" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor

# Alternative: Set ondemand governor for balanced performance
echo "ondemand" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor

# Configure ondemand governor parameters for better responsiveness
echo 10 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate

# Check minimum and maximum frequencies
for cpu in /sys/devices/system/cpu/cpu*/cpufreq/; do
    if [ -f "$cpu/scaling_min_freq" ]; then
        echo "CPU $(basename $(dirname $cpu)): Min $(cat $cpu/scaling_min_freq) Max $(cat $cpu/scaling_max_freq)"
    fi
done

# Set custom frequency limits (optional)
# Set minimum frequency to 50% of max for better responsiveness
MAX_FREQ=$(cat /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq)
MIN_FREQ=$((MAX_FREQ / 2))
echo $MIN_FREQ | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_min_freq

# Make governor settings persistent
cat > /etc/local.d/cpu-performance.start << 'EOF'
#!/bin/sh
# CPU Performance Optimization

# Set CPU governor
echo "ondemand" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor > /dev/null 2>&1

# Configure ondemand parameters
echo 10 > /sys/devices/system/cpu/cpufreq/ondemand/up_threshold 2>/dev/null
echo 50000 > /sys/devices/system/cpu/cpufreq/ondemand/sampling_rate 2>/dev/null

# Disable CPU power saving for performance
echo 1 > /sys/devices/system/cpu/sched_mc_power_savings 2>/dev/null
echo 1 > /sys/devices/system/cpu/sched_smt_power_savings 2>/dev/null

# Set I/O scheduler for better CPU efficiency
for disk in /sys/block/sd*; do
    if [ -f "$disk/queue/scheduler" ]; then
        echo "deadline" > "$disk/queue/scheduler" 2>/dev/null
    fi
done
EOF

chmod +x /etc/local.d/cpu-performance.start
rc-update add local default

# Create CPU monitoring script
cat > /usr/local/bin/cpu-monitor.sh << 'EOF'
#!/bin/bash
# CPU Performance Monitor

while true; do
    clear
    echo "⚡ CPU PERFORMANCE MONITOR - $(date)"
    echo "================================="
    echo
    
    echo "🔥 Current CPU Frequencies:"
    for i in $(seq 0 $(($(nproc)-1))); do
        if [ -f "/sys/devices/system/cpu/cpu$i/cpufreq/scaling_cur_freq" ]; then
            freq=$(cat /sys/devices/system/cpu/cpu$i/cpufreq/scaling_cur_freq)
            freq_mhz=$((freq / 1000))
            echo "  CPU $i: ${freq_mhz} MHz"
        fi
    done
    echo
    
    echo "⚙️ CPU Governors:"
    for i in $(seq 0 $(($(nproc)-1))); do
        if [ -f "/sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor" ]; then
            gov=$(cat /sys/devices/system/cpu/cpu$i/cpufreq/scaling_governor)
            echo "  CPU $i: $gov"
        fi
    done
    echo
    
    echo "📊 CPU Usage per Core:"
    grep "cpu[0-9]" /proc/stat | head -$(nproc) | awk '{
        cpu=$1; user=$2; nice=$3; system=$4; idle=$5; 
        total=user+nice+system+idle; 
        usage=100*(total-idle)/total; 
        printf "  %s: %.1f%%\n", cpu, usage
    }'
    echo
    
    echo "📈 Load Average:"
    uptime | awk -F'load average:' '{print "  " $2}'
    echo
    
    echo "🌡️ CPU Temperature (if available):"
    sensors 2>/dev/null | grep "Core" | head -$(nproc) || echo "  Temperature sensors not available"
    echo
    
    echo "Press Ctrl+C to exit, refreshing in 2 seconds..."
    sleep 2
done
EOF

chmod +x /usr/local/bin/cpu-monitor.sh

CPU governor options:

  • performance: Maximum frequency always (high performance, high power)
  • powersave: Minimum frequency always (low performance, low power)
  • ondemand: Dynamic scaling based on load (balanced)
  • conservative: Similar to ondemand but slower scaling
  • schedutil: Kernel scheduler-driven scaling (modern)

What this means: Your CPU frequency scaling is optimized for your workload! 🎉

🎮 Step 3: Optimize CPU Scheduling

Configure Process Scheduling

Let’s optimize how your CPU handles processes! 🎯

What we’re doing: Configuring the Linux scheduler to prioritize tasks effectively and reduce latency for better overall performance.

# Check current scheduler information
cat /proc/sys/kernel/sched_domain/cpu0/domain0/name 2>/dev/null || echo "Scheduler domain info not available"
cat /proc/sys/kernel/sched_child_runs_first
cat /proc/sys/kernel/sched_latency_ns

# Configure scheduler for better desktop responsiveness
echo 1 > /proc/sys/kernel/sched_child_runs_first
echo 6000000 > /proc/sys/kernel/sched_latency_ns  # 6ms
echo 1000000 > /proc/sys/kernel/sched_min_granularity_ns  # 1ms
echo 3000000 > /proc/sys/kernel/sched_wakeup_granularity_ns  # 3ms

# Enable automatic NUMA balancing (if NUMA available)
echo 1 > /proc/sys/kernel/numa_balancing 2>/dev/null || echo "NUMA balancing not available"

# Optimize for CPU-bound workloads
echo 0 > /proc/sys/kernel/sched_migration_cost_ns
echo 500000 > /proc/sys/kernel/sched_nr_migrate

# Create optimized kernel parameters file
cat > /etc/sysctl.d/99-cpu-performance.conf << 'EOF'
# CPU Performance Optimizations

# Scheduler settings for better responsiveness
kernel.sched_child_runs_first = 1
kernel.sched_latency_ns = 6000000
kernel.sched_min_granularity_ns = 1000000
kernel.sched_wakeup_granularity_ns = 3000000
kernel.sched_migration_cost_ns = 0
kernel.sched_nr_migrate = 32

# Reduce context switch overhead
kernel.sched_autogroup_enabled = 1

# NUMA optimizations (if available)
kernel.numa_balancing = 1

# CPU isolation for real-time tasks (adjust CPU numbers as needed)
# kernel.isolcpus = 2,3

# Prevent unnecessary interrupts
kernel.nmi_watchdog = 0

# Optimize for throughput vs latency
vm.dirty_ratio = 40
vm.dirty_background_ratio = 10
vm.dirty_expire_centisecs = 3000
vm.dirty_writeback_centisecs = 500

# Network optimizations that help CPU
net.core.netdev_max_backlog = 5000
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216
EOF

# Apply the settings
sysctl -p /etc/sysctl.d/99-cpu-performance.conf

# Set up process priorities and nice values
cat > /usr/local/bin/cpu-priority-manager.sh << 'EOF'
#!/bin/bash
# CPU Priority Management Script

# Function to set process priorities
set_process_priority() {
    local process_name="$1"
    local nice_value="$2"
    local ionice_class="$3"
    local ionice_level="$4"
    
    # Find and adjust process priorities
    for pid in $(pgrep "$process_name"); do
        # Set CPU priority
        renice "$nice_value" "$pid" 2>/dev/null
        
        # Set I/O priority if ionice is available
        if command -v ionice >/dev/null; then
            ionice -c "$ionice_class" -n "$ionice_level" -p "$pid" 2>/dev/null
        fi
        
        echo "Adjusted priority for $process_name (PID: $pid) - Nice: $nice_value, I/O: $ionice_class/$ionice_level"
    done
}

# High priority for system critical processes
set_process_priority "kworker" -5 1 2
set_process_priority "ksoftirqd" -5 1 2
set_process_priority "migration" -10 1 1

# Normal priority for user applications
set_process_priority "nginx" 0 2 4
set_process_priority "apache" 0 2 4
set_process_priority "mysql" -2 2 3

# Lower priority for background tasks
set_process_priority "rsync" 10 3 7
set_process_priority "backup" 15 3 7
set_process_priority "updatedb" 19 3 7

# CPU affinity for specific processes (bind to specific cores)
# Useful for multi-core systems
bind_process_to_cores() {
    local process_name="$1"
    local core_list="$2"
    
    for pid in $(pgrep "$process_name"); do
        taskset -cp "$core_list" "$pid" 2>/dev/null && \
        echo "Bound $process_name (PID: $pid) to cores: $core_list"
    done
}

# Example: Bind nginx to cores 0,1 and database to cores 2,3
# bind_process_to_cores "nginx" "0,1"
# bind_process_to_cores "mysql" "2,3"

echo "CPU priority management completed at $(date)"
EOF

chmod +x /usr/local/bin/cpu-priority-manager.sh

# Set up cron job for priority management
echo "*/10 * * * * /usr/local/bin/cpu-priority-manager.sh >/dev/null 2>&1" >> /etc/crontabs/root

Scheduler optimizations applied:

  • Reduced latency for interactive tasks
  • Improved process migration efficiency
  • Better CPU affinity management
  • Optimized context switching overhead

What this creates:

Process priorities: Automatically managed
CPU affinity:      Processes bound to specific cores
Scheduler latency: Reduced from 24ms to 6ms
Context switches:  Optimized for performance

Great job! CPU scheduling is optimized! 🌟

📊 Step 4: Advanced CPU Optimizations

Fine-tune CPU Features

Now let’s enable advanced CPU features for maximum performance! 😊

What we’re doing: Configuring advanced processor features like hyper-threading, turbo boost, and CPU-specific optimizations.

# Check CPU features and capabilities
grep -m1 "flags" /proc/cpuinfo | tr ' ' '\n' | grep -E "(ht|lm|sse|avx|aes)" | sort

# Check for Intel/AMD specific features
vendor=$(grep -m1 "vendor_id" /proc/cpuinfo | awk '{print $3}')
echo "CPU Vendor: $vendor"

# Intel-specific optimizations
if echo "$vendor" | grep -q "Intel"; then
    echo "Applying Intel-specific optimizations..."
    
    # Enable Intel Turbo Boost (if available)
    echo 1 > /sys/devices/system/cpu/intel_pstate/no_turbo 2>/dev/null && echo "Turbo Boost enabled" || echo "Turbo Boost control not available"
    
    # Set Intel P-State driver preferences
    if [ -f /sys/devices/system/cpu/intel_pstate/status ]; then
        echo "active" > /sys/devices/system/cpu/intel_pstate/status
        echo "Intel P-State driver activated"
    fi
    
    # Configure Intel specific governors
    if [ -f /sys/devices/system/cpu/cpufreq/policy0/energy_performance_preference ]; then
        echo "performance" > /sys/devices/system/cpu/cpufreq/policy*/energy_performance_preference
        echo "Energy performance preference set to performance"
    fi
fi

# AMD-specific optimizations
if echo "$vendor" | grep -q "AMD"; then
    echo "Applying AMD-specific optimizations..."
    
    # Enable AMD Boost (if available)
    echo 0 > /sys/devices/system/cpu/cpufreq/boost 2>/dev/null || echo "AMD Boost control not available"
    
    # Set AMD-specific kernel parameters
    echo "AMD-specific optimizations applied"
fi

# Configure CPU isolation for real-time performance
create_cpu_isolation() {
    local isolated_cpus="$1"
    
    cat > /etc/default/grub.d/cpu-isolation.cfg << EOF
# CPU Isolation for Real-time Performance
GRUB_CMDLINE_LINUX_DEFAULT="\$GRUB_CMDLINE_LINUX_DEFAULT isolcpus=$isolated_cpus nohz_full=$isolated_cpus rcu_nocbs=$isolated_cpus"
EOF
    
    echo "CPU isolation configured for cores: $isolated_cpus"
    echo "Reboot required to apply isolation settings"
}

# Example: Isolate last 2 CPUs for real-time tasks
# total_cpus=$(nproc)
# isolated_cpus="$((total_cpus-2))-$((total_cpus-1))"
# create_cpu_isolation "$isolated_cpus"

# Optimize interrupt handling
cat > /usr/local/bin/irq-balance.sh << 'EOF'
#!/bin/bash
# IRQ Balancing for CPU Performance

# Install irqbalance if not available
which irqbalance >/dev/null || apk add irqbalance

# Configure IRQ balancing
cat > /etc/default/irqbalance << 'EOL'
# IRQ balance configuration
ENABLED=1
ONESHOT=0

# Banned CPUs (isolate these from interrupts)
# IRQBALANCE_BANNED_CPUS=0000000c

# Policy for IRQ distribution
IRQBALANCE_ARGS="--policyscript=/usr/local/bin/irq-policy.sh"
EOL

# Create IRQ policy script
cat > /usr/local/bin/irq-policy.sh << 'EOL'
#!/bin/bash
# Custom IRQ distribution policy

case "$1" in
    # Network interrupts to CPU 0-1
    *eth*|*wlan*)
        echo "package 0"
        ;;
    # Storage interrupts to CPU 2-3
    *sd*|*nvme*)
        echo "package 1"
        ;;
    # Default distribution
    *)
        echo "any"
        ;;
esac
EOL

chmod +x /usr/local/bin/irq-policy.sh

# Start IRQ balancing
rc-service irqbalance start 2>/dev/null || echo "irqbalance service not available"
rc-update add irqbalance default 2>/dev/null || echo "irqbalance autostart not set"

echo "IRQ balancing configured"
EOF

chmod +x /usr/local/bin/irq-balance.sh
/usr/local/bin/irq-balance.sh

# Create CPU cache optimization
optimize_cpu_cache() {
    echo "Optimizing CPU cache usage..."
    
    # Disable CPU cache prefetch for latency-sensitive applications
    echo 0 > /proc/sys/vm/zone_reclaim_mode
    
    # Optimize memory allocation for CPU cache efficiency
    echo 1 > /proc/sys/vm/compact_memory 2>/dev/null || echo "Memory compaction not available"
    
    # Configure kernel same-page merging for cache efficiency
    echo 1 > /sys/kernel/mm/ksm/run 2>/dev/null || echo "KSM not available"
    echo 100 > /sys/kernel/mm/ksm/pages_to_scan 2>/dev/null
    echo 1000 > /sys/kernel/mm/ksm/sleep_millisecs 2>/dev/null
    
    echo "CPU cache optimizations applied"
}

optimize_cpu_cache

# Monitor and log CPU performance metrics
cat > /usr/local/bin/cpu-performance-logger.sh << 'EOF'
#!/bin/bash
# CPU Performance Data Logger

LOG_FILE="/var/log/cpu-performance.log"
INTERVAL=60  # Log every 60 seconds

log_cpu_metrics() {
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local load_avg=$(cat /proc/loadavg | awk '{print $1","$2","$3}')
    local cpu_freq=""
    local cpu_temp=""
    
    # Get average CPU frequency
    if ls /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq >/dev/null 2>&1; then
        cpu_freq=$(cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq | awk '{sum+=$1; count++} END {print sum/count/1000}')
    else
        cpu_freq="N/A"
    fi
    
    # Get CPU temperature if available
    cpu_temp=$(sensors 2>/dev/null | grep "Core 0" | awk '{print $3}' | tr -d '+°C' | head -1)
    [ -z "$cpu_temp" ] && cpu_temp="N/A"
    
    # Get CPU usage percentage
    cpu_usage=$(top -bn1 | grep "^%Cpu" | awk '{print $2}' | tr -d '%us,')
    
    # Get context switches per second
    context_switches=$(vmstat 1 2 | tail -1 | awk '{print $12}')
    
    # Get interrupts per second
    interrupts=$(vmstat 1 2 | tail -1 | awk '{print $11}')
    
    # Log format: timestamp,load_1m,load_5m,load_15m,cpu_freq_mhz,cpu_temp,cpu_usage,context_switches,interrupts
    echo "$timestamp,$load_avg,$cpu_freq,$cpu_temp,$cpu_usage,$context_switches,$interrupts" >> "$LOG_FILE"
}

# Create log file header if it doesn't exist
if [ ! -f "$LOG_FILE" ]; then
    echo "timestamp,load_1m,load_5m,load_15m,cpu_freq_mhz,cpu_temp_c,cpu_usage_pct,context_switches_sec,interrupts_sec" > "$LOG_FILE"
fi

# Log current metrics
log_cpu_metrics

# If run with "daemon" parameter, run continuously
if [ "$1" = "daemon" ]; then
    while true; do
        sleep "$INTERVAL"
        log_cpu_metrics
    done
fi
EOF

chmod +x /usr/local/bin/cpu-performance-logger.sh

# Start performance logging
/usr/local/bin/cpu-performance-logger.sh

# Add to cron for continuous logging
echo "*/1 * * * * /usr/local/bin/cpu-performance-logger.sh >/dev/null 2>&1" >> /etc/crontabs/root

Advanced optimizations applied:

  • Vendor-specific CPU features enabled
  • Interrupt balancing optimized
  • CPU cache utilization improved
  • Performance metrics logging enabled

What this does: Unlocks your CPU’s full potential with advanced optimizations! 📚

Example: CPU Stress Testing and Benchmarking 🟡

What we’re doing: Running comprehensive stress tests to validate CPU performance improvements.

# Install benchmarking tools
apk add stress-ng sysbench

# Create comprehensive CPU benchmark script
cat > /usr/local/bin/cpu-benchmark.sh << 'EOF'
#!/bin/bash
# Comprehensive CPU Benchmarking Suite

RESULTS_FILE="/var/log/cpu-benchmark-$(date +%Y%m%d-%H%M%S).log"

echo "⚡ CPU BENCHMARK SUITE - $(date)" | tee $RESULTS_FILE
echo "=================================" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

# System information
echo "🖥️ System Information:" | tee -a $RESULTS_FILE
echo "CPU: $(grep -m1 'model name' /proc/cpuinfo | cut -d: -f2 | sed 's/^ *//')" | tee -a $RESULTS_FILE
echo "Cores: $(nproc)" | tee -a $RESULTS_FILE
echo "Current Governor: $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo 'N/A')" | tee -a $RESULTS_FILE
echo "Current Frequency: $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq 2>/dev/null | awk '{print $1/1000 " MHz"}' || echo 'N/A')" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

# Baseline measurements
echo "📊 Baseline Measurements:" | tee -a $RESULTS_FILE
echo "Load Average: $(cat /proc/loadavg)" | tee -a $RESULTS_FILE
echo "Context Switches: $(vmstat 1 2 | tail -1 | awk '{print $12 "/sec"}')" | tee -a $RESULTS_FILE
echo "Interrupts: $(vmstat 1 2 | tail -1 | awk '{print $11 "/sec"}')" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

# CPU integer performance test
echo "🔢 CPU Integer Performance Test (30s):" | tee -a $RESULTS_FILE
stress_ng_int=$(stress-ng --cpu $(nproc) --cpu-method int32 --metrics-brief --timeout 30s 2>&1 | grep "bogo ops" | awk '{print $4}')
echo "Integer operations: $stress_ng_int bogo ops/sec" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

# CPU floating point performance test
echo "🧮 CPU Floating Point Performance Test (30s):" | tee -a $RESULTS_FILE
stress_ng_fp=$(stress-ng --cpu $(nproc) --cpu-method float64 --metrics-brief --timeout 30s 2>&1 | grep "bogo ops" | awk '{print $4}')
echo "Floating point operations: $stress_ng_fp bogo ops/sec" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

# Memory bandwidth test
echo "💾 Memory Bandwidth Test:" | tee -a $RESULTS_FILE
sysbench_memory=$(sysbench memory --threads=$(nproc) --time=30 --memory-total-size=1G run 2>/dev/null | grep "transferred" | awk '{print $3 " " $4}')
echo "Memory throughput: $sysbench_memory" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

# Context switch performance
echo "🔄 Context Switch Performance Test:" | tee -a $RESULTS_FILE
context_switch_rate=$(stress-ng --switch $(nproc) --metrics-brief --timeout 10s 2>&1 | grep "bogo ops" | awk '{print $4}')
echo "Context switches: $context_switch_rate switches/sec" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

# Cache performance test
echo "🧠 CPU Cache Performance Test:" | tee -a $RESULTS_FILE
cache_perf=$(stress-ng --cache $(nproc) --metrics-brief --timeout 20s 2>&1 | grep "bogo ops" | awk '{print $4}')
echo "Cache operations: $cache_perf bogo ops/sec" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

# Multi-core scaling test
echo "🚀 Multi-core Scaling Test:" | tee -a $RESULTS_FILE
for cores in 1 2 4 $(nproc); do
    if [ $cores -le $(nproc) ]; then
        scaling_result=$(stress-ng --cpu $cores --cpu-method int32 --metrics-brief --timeout 10s 2>&1 | grep "bogo ops" | awk '{print $4}')
        echo "  $cores cores: $scaling_result bogo ops/sec" | tee -a $RESULTS_FILE
    fi
done
echo | tee -a $RESULTS_FILE

# Post-test measurements
echo "📈 Post-test System State:" | tee -a $RESULTS_FILE
echo "Load Average: $(cat /proc/loadavg)" | tee -a $RESULTS_FILE
echo "Temperature: $(sensors 2>/dev/null | grep "Core 0" | awk '{print $3}' || echo 'N/A')" | tee -a $RESULTS_FILE
echo "CPU Frequency: $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq 2>/dev/null | awk '{print $1/1000 " MHz"}' || echo 'N/A')" | tee -a $RESULTS_FILE
echo | tee -a $RESULTS_FILE

echo "✅ Benchmark completed. Results saved to: $RESULTS_FILE" | tee -a $RESULTS_FILE
echo "View results: cat $RESULTS_FILE"
EOF

chmod +x /usr/local/bin/cpu-benchmark.sh

# Run initial benchmark
echo "Running CPU benchmark to test optimizations..."
/usr/local/bin/cpu-benchmark.sh

# Create performance comparison script
cat > /usr/local/bin/cpu-compare.sh << 'EOF'
#!/bin/bash
# Compare CPU performance before and after optimizations

BEFORE_FILE="$1"
AFTER_FILE="$2"

if [ -z "$BEFORE_FILE" ] || [ -z "$AFTER_FILE" ]; then
    echo "Usage: $0 <before_benchmark_file> <after_benchmark_file>"
    exit 1
fi

echo "🔬 CPU PERFORMANCE COMPARISON"
echo "============================="
echo

echo "📊 Performance Improvements:"
echo

# Extract and compare integer performance
before_int=$(grep "Integer operations" "$BEFORE_FILE" | awk '{print $3}')
after_int=$(grep "Integer operations" "$AFTER_FILE" | awk '{print $3}')
int_improvement=$(echo "scale=2; ($after_int - $before_int) / $before_int * 100" | bc 2>/dev/null || echo "N/A")
echo "Integer Performance: $before_int → $after_int bogo ops/sec (+${int_improvement}%)"

# Extract and compare floating point performance
before_fp=$(grep "Floating point operations" "$BEFORE_FILE" | awk '{print $4}')
after_fp=$(grep "Floating point operations" "$AFTER_FILE" | awk '{print $4}')
fp_improvement=$(echo "scale=2; ($after_fp - $before_fp) / $before_fp * 100" | bc 2>/dev/null || echo "N/A")
echo "Floating Point Performance: $before_fp → $after_fp bogo ops/sec (+${fp_improvement}%)"

# Extract and compare context switch performance
before_ctx=$(grep "Context switches" "$BEFORE_FILE" | awk '{print $3}')
after_ctx=$(grep "Context switches" "$AFTER_FILE" | awk '{print $3}')
ctx_improvement=$(echo "scale=2; ($after_ctx - $before_ctx) / $before_ctx * 100" | bc 2>/dev/null || echo "N/A")
echo "Context Switch Performance: $before_ctx → $after_ctx switches/sec (+${ctx_improvement}%)"

echo
echo "✅ Optimization Summary:"
echo "  • CPU frequency scaling optimized"
echo "  • Process scheduling tuned"
echo "  • Interrupt balancing configured"
echo "  • Cache utilization improved"
EOF

chmod +x /usr/local/bin/cpu-compare.sh

What this does: Provides comprehensive benchmarking to measure your CPU optimization results! 🌟

🚨 Fix Common Problems

Problem 1: CPU overheating after optimization ❌

What happened: Aggressive performance settings cause thermal issues. How to fix it: Implement thermal throttling and monitoring!

# Check CPU temperature
sensors | grep -E "(Core|temp)"

# Reset to conservative governor if overheating
echo "conservative" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor

# Set temperature-based throttling
cat > /usr/local/bin/thermal-protection.sh << 'EOF'
#!/bin/bash
TEMP_THRESHOLD=70  # Celsius
CURRENT_TEMP=$(sensors | grep "Core 0" | awk '{print $3}' | tr -d '+°C')

if [ "$CURRENT_TEMP" -gt "$TEMP_THRESHOLD" ]; then
    echo "powersave" > /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
fi
EOF

chmod +x /usr/local/bin/thermal-protection.sh
echo "*/1 * * * * /usr/local/bin/thermal-protection.sh" >> /etc/crontabs/root

Problem 2: System instability with aggressive settings ❌

What happened: CPU optimizations cause crashes or freezes. How to fix it: Gradually apply optimizations and test stability!

# Reset to safe defaults
echo "ondemand" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor
echo 6000000 > /proc/sys/kernel/sched_latency_ns

# Test stability with stress testing
stress-ng --cpu $(nproc) --timeout 300s --verify

# Apply optimizations one at a time
echo "Apply optimizations gradually and test each change"

Problem 3: Performance regression ❌

What happened: Optimizations made performance worse. How to fix it: Revert changes and analyze the workload!

# Restore default kernel parameters
sysctl -p /etc/sysctl.conf

# Reset CPU governor to default
echo "ondemand" | tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor

# Analyze workload characteristics
echo "Check if workload is I/O bound rather than CPU bound"
iostat -x 1 5

Don’t worry! These problems happen to everyone. You’re doing great! 💪

💡 Simple Tips

  1. Monitor temperature 📅 - Keep CPU cool for stable performance
  2. Test incrementally 🌱 - Apply one optimization at a time
  3. Benchmark regularly 🤝 - Measure performance changes
  4. Match workload 💪 - Optimize for your specific use case

✅ Check Everything Works

Let’s make sure everything is working:

# Check CPU frequency scaling
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor | head -1

# Check current CPU frequencies
cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq | awk '{print $1/1000 " MHz"}'

# Check CPU load and usage
uptime
top -bn1 | grep "^%Cpu"

# Check scheduler settings
cat /proc/sys/kernel/sched_latency_ns

# Run quick performance test
stress-ng --cpu 1 --timeout 10s --metrics-brief | grep "bogo ops"

# Check temperature
sensors 2>/dev/null | grep "Core" | head -1 || echo "Temperature monitoring not available"

# View performance log
tail -5 /var/log/cpu-performance.log

# You should see this
echo "CPU performance tuning is complete and working optimally! ✅"

Good output:

ondemand
1800 MHz
1900 MHz
2100 MHz
1950 MHz

load average: 0.25, 0.30, 0.28
%Cpu(s):  2.1 us,  1.2 sy,  0.0 ni, 96.5 id,  0.2 wa,  0.0 hi,  0.0 si,  0.0 st

6000000

stress-ng: info:  [12345] dispatching hogs: 1 cpu
stress-ng: info:  [12345] successful run completed in 10.01s
cpu: 125000 bogo ops/sec

Core 0: +45.0°C (high = +100.0°C, crit = +100.0°C)

2025-06-03 18:45:32,0.25,0.30,0.28,1875,45,2.1,150,90

✅ Success! CPU is running at optimal performance with proper thermal management.

🏆 What You Learned

Great job! Now you can:

  • ✅ Configure CPU frequency scaling for optimal performance
  • ✅ Tune process scheduling for reduced latency
  • ✅ Enable advanced CPU features and optimizations
  • ✅ Implement performance monitoring and benchmarking
  • ✅ Handle thermal management and stability issues

🎯 What’s Next?

Now you can try:

  • 📚 Implementing real-time kernel patches for ultra-low latency
  • 🛠️ Setting up CPU profiling and bottleneck analysis
  • 🤝 Creating workload-specific optimization profiles
  • 🌟 Building automated performance tuning systems!

Remember: Every expert was once a beginner. You’re doing amazing! 🎉

Keep practicing and you’ll become a performance tuning expert too! 💫