Fedora Linux 如何減少閒置 RAM:服務控制器、ZRAM 調校及 x86-64-v4 編譯完整指南
Cut Idle RAM on Fedora Linux: A Complete Service Controller, ZRAM Tuning & x86-64-v4 Compilation Guide
Fedora Workstation 預設執行的背景服務合共會佔用 600 MB 至 1.2+ GB 閒置 RAM;指南提供 Python CLI service_control.py,用來管理服務及按需回收記憶體。控制器可記錄服務原有狀態,並提供 ZRAM、核心記憶體及電源調校。指南亦涵蓋在 Fedora 下載原始碼並以 x86-64-v4(AVX-512)重新編譯應用程式。
Fedora Workstation is one of the best-engineered Linux desktops out there, but out of the box it ships like a Swiss Army knife built for every enterprise and consumer hardware scenario imaginable.
Even if you are running a modern single-NVMe laptop with no printer, no smartcard reader, no cellular modem, and no RAID array, Fedora quietly runs over a dozen background daemons, D-Bus watchers, and metadata pollers. Together, services like PackageKit, gnome-software, localsearch-3, abrt, colord, and cups routinely consume 600 MB to 1.2+ GB of idle RAM and trigger constant CPU wakeups that drain battery life.
Instead of running scattered systemctl commands that you will forget next week—or risking breaking system dependencies—I built a single, reversible Python CLI (service_control.py) to manage hardware services, reclaim RAM on demand, and toggle between Maximum Performance and Ultra-Battery modes without rebooting.
In this guide, we will cover:
- Which Fedora background services are safe to cut (and how much RAM they save).
- Kernel & ZRAM memory tuning to squeeze more multitasking headroom out of 8 GB and 16 GB laptops.
-
How the controller works (
maskvs.disableand state snapshots) + the complete drop-in source code. -
How to download source code and recompile apps with
x86-64-v4(AVX-512) on Fedora—including the real-world pros and cons.
1. What Gets Cut & How Much RAM You Reclaim
By default, systemd uses socket activation and D-Bus activation. Even if you run systemctl disable, another process can silently wake a daemon back up in the background. Using systemctl mask symlinks the unit to /dev/null, guaranteeing 0 MB RAM and 0% CPU until you explicitly unmask it.
Here are the safe, high-impact targets managed by the controller:
| Target Key | Systemd Unit(s) | Scope | What It Does & Why You Probably Don't Need It | Typical RAM Saved |
|---|---|---|---|---|
packagekit |
packagekit.service |
System | Background DNF metadata daemon used by GNOME Software; locks DNF and eats huge RAM. | 150 – 400 MB |
indexer |
localsearch-3.service |
User | Tracker/LocalSearch file content indexer; spikes CPU/disk I/O when downloading files. | 80 – 250 MB |
abrt |
abrtd, abrt-oops, abrt-xorg
|
System | Fedora's Automatic Bug Reporting Tool; constantly watches system journals for crashes. | 40 – 90 MB |
cups |
cups.service, .socket, .path
|
System | Local printing server; unnecessary if you rarely or never print. | 25 – 60 MB |
bluetooth |
bluetooth.service |
System | Bluetooth stack and radio controller; keep masked when using wired peripherals. | 15 – 30 MB |
modem-manager |
ModemManager.service |
System | Mobile broadband / cellular SIM hardware manager. | 25 – 45 MB |
color-profile |
colord.service |
System | Display colorimeter & printer ICC profile daemon. | 15 – 30 MB |
avahi |
avahi-daemon.service, .socket
|
System | ZeroConf/mDNS local .local network discovery; reduces network wakeups on public Wi-Fi. |
10 – 20 MB |
geoclue |
geoclue.service |
System | System-wide geolocation tracking service. | 15 – 25 MB |
usb-media |
gvfs-gphoto2, gvfs-afc, gvfs-mtp
|
User | Auto-mount watchers for digital cameras, iPhones, and MTP devices. | 20 – 40 MB |
smartcard |
gsd-smartcard.service |
User | Corporate CAC / physical smartcard insertion watcher. | 10 – 15 MB |
wwan |
gsd-wwan.service |
User | GNOME cellular WWAN settings daemon. | 10 – 15 MB |
stratis |
stratisd.service |
System | Enterprise Stratis storage pool daemon (unused on Fedora's default Btrfs). | 15 – 25 MB |
dnf-poller |
dnf-makecache.timer / .service
|
System | Wakes up every few hours to download repository metadata in the background. | Bandwidth + Wakeups |
raid-check |
raid-check.timer / .service
|
System | Weekly software RAID array scrub (pointless on single-NVMe laptops). | Disk I/O |
Note: On top of these systemd units, killing the background
gnome-software --gapplication-serviceresident process (handled automatically by the script'strim-ramcommand) immediately frees another 250 – 500 MB of RAM.
2. Beyond Services: Kernel, ZRAM & Power Optimizations
Cutting daemons is only half the story. Fedora uses ZRAM (a compressed block device in RAM) instead of a traditional disk swap partition. Many Linux users mistakenly apply old hard-drive swap tweaks (vm.swappiness=10), which actually hurts performance on ZRAM systems.
The upgraded controller includes a trim-ram command that applies three major memory and power optimizations:
-
ZRAM-Optimal Kernel VM Tuning:
-
vm.swappiness=150: Encourages the kernel to compress cold, inactive anonymous pages into ZRAM early, leaving fast uncompressed RAM free for active applications and compilers. -
vm.page-cluster=0: Disables swap read-ahead (which is designed for spinning HDDs, not zero-latency RAM). -
vm.vfs_cache_pressure=50: Keeps filesystem directory/inode caches slightly longer so file searches stay snappy without ballooning memory.
-
-
On-Demand PageCache & Bloat Purge (
trim-ram):- Flushes dirty disk buffers (
sync), drops clean kernel PageCache/dentries/inodes (/proc/sys/vm/drop_caches), and terminates residentgnome-softwarebackground processes before you launch a heavy workload.
- Flushes dirty disk buffers (
-
Instant Hardware Uncapping (
uncapvs.cap):- Uses Fedora's native TuneD daemon (
throughput-performancevs.powersave) alongside PCIe Active State Power Management (ASPM) (defaultvs.powersupersave) so your NVMe SSD and Wi-Fi card enter deep L1 sleep on battery, or run at zero bus latency when plugged in.
- Uses Fedora's native TuneD daemon (
3. Architecture & Workflow Before You Copy the Code
Before dropping the script into your home directory, here is how it is structured so you never lock yourself out of hardware you actually need:
-
Zero Third-Party Dependencies: Uses only Python's standard library (
sys,os,json,subprocess) and built-in Fedora tools (systemctl,tuned-adm,nmcli,upower,sysctl). -
Smart State Snapshots (
~/.service_control_state.json): When you runmask-all, the script records which services were originally active/enabled on your machine. Runningunmask-allrestores your exact prior state rather than blindly enabling daemons you never used. -
Granular On-Demand Toggles: Need to pair Bluetooth headphones or print a document? Run
enable bluetoothorenable cups, do your work, and rundisable bluetoothwhen finished.
Daily Usage Examples
# 1. Mask all redundant background daemons & timers
python3 ~/service_control.py mask-all
# 2. Check live service states and active TuneD profile
python3 ~/service_control.py status
# 3. Reclaim cached RAM, kill gnome-software bloat, and tune ZRAM VM params
python3 ~/service_control.py trim-ram
# 4. Inspect detailed RAM, ZRAM compression ratio, and top memory hogs
python3 ~/service_control.py ram
# 5. Uncap CPU Turbo Boost & disable PCIe sleep for compiling/gaming
python3 ~/service_control.py uncap
# 6. Switch back to Ultra-Battery mode & check live discharge wattage
python3 ~/service_control.py cap
python3 ~/service_control.py power
# 7. Temporarily re-enable Bluetooth when needed
python3 ~/service_control.py enable bluetooth
4. Complete Source Code: service_control.py
Save this file as ~/service_control.py and make it executable (chmod +x ~/service_control.py).
#!/usr/bin/env python3
"""
service_control.py - Master hardware, RAM, service, performance & battery CLI for Fedora Linux.
Includes:
- Instant Uncap (Maximum Performance mode) vs. Cap (Ultra-Battery mode)
- Hardware & service masking/unmasking with automatic state snapshots
- Kernel ZRAM tuning, PageCache purging, and resident bloat cleanup (trim-ram)
- Live RAM/ZRAM telemetry & battery wattage inspection
- Emergency Wi-Fi & NetworkManager reset
"""
import sys
import os
import json
import subprocess
STATE_FILE = os.path.expanduser("~/.service_control_state.json")
# Service & Timer definitions:
SERVICES = {
"packagekit": {
"name": "PackageKit Daemon",
"description": "Background DNF metadata service for GNOME Software (major RAM hog)",
"scope": "system",
"units": ["packagekit.service"]
},
"abrt": {
"name": "ABRT Crash Reporter",
"description": "Automatic Bug Reporting Tool daemons watching system journals",
"scope": "system",
"units": ["abrtd.service", "abrt-oops.service", "abrt-xorg.service"]
},
"cups": {
"name": "CUPS Print Server",
"description": "Background printing spooler & socket listener",
"scope": "system",
"units": ["cups.service", "cups.socket", "cups.path"]
},
"printing": {
"name": "Printer Notifications",
"description": "GNOME background printer discovery & queue notification daemon",
"scope": "user",
"units": ["org.gnome.SettingsDaemon.PrintNotifications.service"]
},
"bluetooth": {
"name": "Bluetooth Service",
"description": "Bluetooth daemon & radio adapter controller",
"scope": "system",
"units": ["bluetooth.service"]
},
"modem-manager": {
"name": "ModemManager",
"description": "Mobile broadband & cellular modem hardware manager",
"scope": "system",
"units": ["ModemManager.service"]
},
"color-profile": {
"name": "Color Management",
"description": "Display colorimeter & printer ICC profile daemon (colord)",
"scope": "system",
"units": ["colord.service"]
},
"avahi": {
"name": "Avahi mDNS/Zeroconf",
"description": "Local .local network discovery daemon (saves RAM & network wakeups)",
"scope": "system",
"units": ["avahi-daemon.service", "avahi-daemon.socket"]
},
"geoclue": {
"name": "Geoclue Location",
"description": "System-wide geolocation tracking daemon",
"scope": "system",
"units": ["geoclue.service"]
},
"smartcard": {
"name": "Smartcard Reader",
"description": "Physical corporate CAC/smartcard insertion watcher",
"scope": "user",
"units": ["org.gnome.SettingsDaemon.Smartcard.service"]
},
"wwan": {
"name": "Cellular WWAN",
"description": "GNOME mobile broadband / cellular SIM daemon",
"scope": "user",
"units": ["org.gnome.SettingsDaemon.Wwan.service"]
},
"stratis": {
"name": "Stratis Storage",
"description": "Stratis enterprise storage daemon (unneeded for standard Btrfs)",
"scope": "system",
"units": ["stratisd.service"]
},
"usb-media": {
"name": "USB Device Auto-Monitors",
"description": "GVFS daemons for cameras (PTP/GPhoto), iPhones (AFC), and MTP",
"scope": "user",
"units": [
"gvfs-gphoto2-volume-monitor.service",
"gvfs-afc-volume-monitor.service",
"gvfs-mtp-volume-monitor.service"
]
},
"indexer": {
"name": "LocalSearch File Indexer",
"description": "Background file indexing daemon for GNOME search (Tracker/LocalSearch)",
"scope": "user",
"units": ["localsearch-3.service"]
},
"dnf-poller": {
"name": "DNF Auto-Cache Timer",
"description": "Background network poller refreshing package lists every few hours",
"scope": "system",
"units": ["dnf-makecache.timer", "dnf-makecache.service"]
},
"raid-check": {
"name": "RAID Integrity Checker",
"description": "Checks software RAID arrays (useless on single NVMe laptops)",
"scope": "system",
"units": ["raid-check.timer", "raid-check.service"]
}
}
def run_cmd(cmd_list):
"""Executes a command quickly and returns (returncode, stdout, stderr)."""
try:
res = subprocess.run(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
return res.returncode, res.stdout.strip(), res.stderr.strip()
except Exception as e:
return 1, "", str(e)
def get_unit_status(unit, scope):
base_cmd = ["systemctl"]
if scope == "user":
base_cmd.append("--user")
_, out, _ = run_cmd(base_cmd + ["is-active", unit])
active = out if out else "unknown"
_, out_en, _ = run_cmd(base_cmd + ["is-enabled", unit])
enabled = out_en if out_en else "unknown"
return active, enabled
def save_snapshot():
"""Saves pre-masking service states so unmask-all can restore accurately."""
if os.path.exists(STATE_FILE):
return
snapshot = {}
for key, info in SERVICES.items():
snapshot[key] = {}
for u in info["units"]:
act, en = get_unit_status(u, info["scope"])
snapshot[key][u] = {"active": act, "enabled": en}
try:
with open(STATE_FILE, "w", encoding="utf-8") as f:
json.dump(snapshot, f, indent=2)
except OSError:
pass
def load_snapshot():
if not os.path.exists(STATE_FILE):
return None
try:
with open(STATE_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except OSError:
return None
def print_help():
print("""
====================================================================================
⚡ service_control.py - Master Fedora Hardware, RAM & Performance Controller
====================================================================================
USAGE:
python3 ~/service_control.py [COMMAND] [TARGET]
🚀 PERFORMANCE & RAM MODES (NO RESTART NEEDED):
uncap Unleash MAXIMUM PERFORMANCE (Turbo active, PCIe bus active)
cap Switch back to ULTRA-BATTERY mode (Powersave, PCIe L1 sleep)
trim-ram Drop clean PageCache, kill GNOME Software bloat & tune ZRAM
fix-wifi Emergency 1-click Wi-Fi reset (restarts NetworkManager & radio)
📊 SYSTEM INSPECTION:
status Show live status of all managed services & timers
ram Show RAM, ZRAM compression stats, VM params & top memory hogs
power Show current battery discharge rate (Watts) and runtime estimate
help Display this help guide
⚙️ SERVICE & TIMER CONTROL:
mask-all Mask ALL redundant services & timers (Max RAM & battery savings)
unmask-all Restore and unmask services back to pre-masking state
disable <target> Stop and mask a specific service or timer
enable <target> Unmask and start a specific service or timer
AVAILABLE TARGETS:
packagekit Background DNF/PackageKit daemon (saves 150-400 MB RAM)
abrt Automatic Bug Reporting Tool crash daemons
cups CUPS background print spooler & socket
printing GNOME printer notification daemon
bluetooth Bluetooth daemon & radio adapter controller
modem-manager Cellular/mobile broadband ModemManager daemon
color-profile Color calibration daemon (colord)
avahi Avahi mDNS/Zeroconf local network discovery
geoclue System geolocation service
smartcard Corporate smartcard reader watcher
wwan GNOME cellular WWAN daemon
stratis Stratis enterprise storage daemon
usb-media USB camera (PTP), iPhone (AFC), and MTP media sync daemons
indexer LocalSearch GNOME background file indexer
dnf-poller DNF background update cache poller
raid-check Software RAID array integrity checker
EXAMPLES:
python3 ~/service_control.py mask-all # Cut all redundant Fedora bloat
python3 ~/service_control.py trim-ram # Reclaim RAM & optimize ZRAM VM
python3 ~/service_control.py uncap # Max CPU/PCIe speed for compiling
python3 ~/service_control.py cap # Back to Ultra-Battery mode
python3 ~/service_control.py enable bluetooth # Turn on Bluetooth when needed
====================================================================================
""")
def cmd_uncap():
print("\n🚀 Switching to MAXIMUM PERFORMANCE MODE (Uncapping)...")
subprocess.run(["sudo", "-v"], check=True)
run_cmd(["sudo", "tuned-adm", "profile", "throughput-performance"])
aspm_path = "/sys/module/pcie_aspm/parameters/policy"
if os.path.exists(aspm_path):
subprocess.run(f"echo default | sudo tee {aspm_path} > /dev/null 2>&1", shell=True)
print("✓ TuneD Profile: throughput-performance (Max Turbo Boost & low scheduler latency)")
print("✓ PCIe ASPM: default (Zero bus sleep latency for NVMe & GPU)")
print("✓ Status: UNCAPPED. System is running at MAXIMUM raw speed.\n")
def cmd_cap():
print("\n🔋 Switching to ULTRA-BATTERY MODE (Capping)...")
subprocess.run(["sudo", "-v"], check=True)
run_cmd(["sudo", "tuned-adm", "profile", "powersave"])
aspm_path = "/sys/module/pcie_aspm/parameters/policy"
if os.path.exists(aspm_path):
subprocess.run(f"echo powersupersave | sudo tee {aspm_path} > /dev/null 2>&1", shell=True)
print("✓ TuneD Profile: powersave (Aggressive frequency downclocking at idle)")
print("✓ PCIe ASPM: powersupersave (NVMe & Wi-Fi enter L1 deep sleep)")
print("✓ Status: CAPPED. Maximum battery life active.\n")
def cmd_trim_ram():
print("\n🧹 Running Deep RAM Reclamation & Fedora ZRAM Optimization...")
subprocess.run(["sudo", "-v"], check=True)
# 1. Flush dirty buffers and drop clean PageCache, dentries, and inodes
run_cmd(["sync"])
subprocess.run("echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null", shell=True)
print("✓ Dropped clean Linux PageCache, dentries, and inodes.")
# 2. Terminate resident gnome-software background service if running
code, _, _ = run_cmd(["pkill", "-f", "gnome-software"])
if code == 0:
print("✓ Terminated resident gnome-software background process (~250-500 MB freed).")
else:
print("✓ gnome-software background process not running.")
# 3. Apply Fedora ZRAM-optimized kernel virtual memory parameters
vm_tweaks = {
"vm.swappiness": "150",
"vm.vfs_cache_pressure": "50",
"vm.page-cluster": "0"
}
for param, val in vm_tweaks.items():
run_cmd(["sudo", "sysctl", "-w", f"{param}={val}"])
print("✓ Tuned ZRAM VM parameters (swappiness=150, page-cluster=0, vfs_cache_pressure=50).\n")
def cmd_ram():
print("\n🧠 Live Fedora Memory & ZRAM Telemetry:")
print("-" * 70)
_, free_out, _ = run_cmd(["free", "-h"])
print(free_out)
print("\n📦 ZRAM Swap Device:")
code, zram_out, _ = run_cmd(["zramctl"])
print(zram_out if (code == 0 and zram_out) else "No active ZRAM device found.")
print("\n⚙️ Kernel VM Parameters:")
for param in ["vm.swappiness", "vm.vfs_cache_pressure", "vm.page-cluster"]:
_, val, _ = run_cmd(["sysctl", "-n", param])
print(f" {param} = {val}")
print("\n🔥 Top 5 RAM-Consuming Processes:")
_, ps_out, _ = run_cmd(["ps", "-eo", "pid,rss,comm", "--sort=-rss"])
for line in ps_out.splitlines()[:6]:
parts = line.split(None, 2)
if len(parts) == 3 and parts[1].isdigit():
mb = int(parts[1]) / 1024
print(f" PID {parts[0]:<7} {mb:>7.1f} MB {parts[2]}")
else:
print(f" {line}")
print("-" * 70 + "\n")
def cmd_fix_wifi():
print("\n📶 Running Emergency Wi-Fi & Network Reset...")
subprocess.run(["sudo", "-v"], check=True)
run_cmd(["nmcli", "radio", "wifi", "off"])
run_cmd(["sudo", "systemctl", "restart", "NetworkManager.service"])
run_cmd(["nmcli", "radio", "wifi", "on"])
print("✓ NetworkManager restarted.")
print("✓ Wi-Fi radio reset and re-enabled.\n")
def cmd_power():
print("\n⚡ Reading live battery power telemetry...")
code, out, _ = run_cmd(["upower", "-i", "/org/freedesktop/UPower/devices/battery_BAT0"])
if code == 0:
for line in out.splitlines():
if any(k in line for k in ["state", "energy-rate", "percentage", "time to empty", "voltage"]):
print(" ", line.strip())
else:
print("Could not read battery device (on AC power or UPower unavailable).")
print()
def cmd_status():
print("\n" + "=" * 72)
print(f"{'TARGET KEY':<16} {'SERVICE / TIMER NAME':<28} {'STATE':<12} {'MASKED?'}")
print("=" * 72)
for key, info in SERVICES.items():
states = []
masked_states = []
for u in info["units"]:
act, en = get_unit_status(u, info["scope"])
states.append(act)
masked_states.append("YES (Masked)" if en == "masked" else "No")
main_act = states[0] if states else "unknown"
main_mask = "YES (Masked)" if any("YES" in m for m in masked_states) else "No"
act_display = f"\033[92m{main_act}\033[0m" if main_act == "active" else f"\033[90m{main_act}\033[0m"
mask_display = f"\033[93m{main_mask}\033[0m" if "YES" in main_mask else main_mask
print(f"{key:<16} {info['name']:<28} {act_display:<20} {mask_display}")
_, profile, _ = run_cmd(["tuned-adm", "active"])
print("=" * 72)
print(f"Active Power Mode: {profile if profile else 'Unknown'}")
print("=" * 72 + "\n")
def disable_target(key):
if key not in SERVICES:
print(f"Error: Unknown target '{key}'. Run 'python3 ~/service_control.py help' for valid targets.")
return False
info = SERVICES[key]
scope = info["scope"]
print(f"Stopping & masking {info['name']} ({key})...")
for u in info["units"]:
if scope == "system":
cmd_stop = ["sudo", "systemctl", "stop", u]
cmd_mask = ["sudo", "systemctl", "mask", u]
else:
cmd_stop = ["systemctl", "--user", "stop", u]
cmd_mask = ["systemctl", "--user", "mask", u]
run_cmd(cmd_stop)
run_cmd(cmd_mask)
print(f"✓ {info['name']} is now STOPPED and MASKED (0 MB RAM / 0% CPU).")
return True
def enable_target(key, snapshot=None):
if key not in SERVICES:
print(f"Error: Unknown target '{key}'. Run 'python3 ~/service_control.py help' for valid targets.")
return False
info = SERVICES[key]
scope = info["scope"]
print(f"Unmasking & restoring {info['name']} ({key})...")
for u in info["units"]:
if scope == "system":
cmd_unmask = ["sudo", "systemctl", "unmask", u]
cmd_start = ["sudo", "systemctl", "start", u]
else:
cmd_unmask = ["systemctl", "--user", "unmask", u]
cmd_start = ["systemctl", "--user", "start", u]
run_cmd(cmd_unmask)
# Only start unit if no snapshot exists OR it was originally active
should_start = True
if snapshot and key in snapshot and u in snapshot[key]:
should_start = snapshot[key][u].get("active") == "active"
if should_start:
run_cmd(cmd_start)
print(f"✓ {info['name']} is now UNMASKED and restored.")
return True
def cmd_mask_all():
print("\n>>> Activating Maximum Optimization Mode (Masking all redundant services & timers)...")
subprocess.run(["sudo", "-v"], check=True)
save_snapshot()
for k in SERVICES.keys():
disable_target(k)
print("\n✓ All redundant background services & timers successfully masked!\n")
def cmd_unmask_all():
print("\n>>> Restoring all managed services & timers back to default...")
subprocess.run(["sudo", "-v"], check=True)
snapshot = load_snapshot()
for k in SERVICES.keys():
enable_target(k, snapshot=snapshot)
if os.path.exists(STATE_FILE):
try:
os.remove(STATE_FILE)
except OSError:
pass
print("\n✓ All services restored!\n")
def main():
if len(sys.argv) < 2:
print_help()
return
action = sys.argv[1].lower().strip()
if action in ["help", "-h", "--help"]:
print_help()
elif action == "status":
cmd_status()
elif action == "ram":
cmd_ram()
elif action == "trim-ram":
cmd_trim_ram()
elif action == "uncap":
cmd_uncap()
elif action == "cap":
cmd_cap()
elif action in ["fix-wifi", "wifi-fix", "reset-wifi"]:
cmd_fix_wifi()
elif action == "power":
cmd_power()
elif action in ["mask-all", "maskall", "disable-all"]:
cmd_mask_all()
cmd_status()
elif action in ["unmask-all", "unmaskall", "enable-all"]:
cmd_unmask_all()
cmd_status()
elif action in ["disable", "mask"]:
if len(sys.argv) < 3:
print("Error: Missing target name. Example: python3 ~/service_control.py disable packagekit")
return
disable_target(sys.argv[2].lower().strip())
elif action in ["enable", "unmask"]:
if len(sys.argv) < 3:
print("Error: Missing target name. Example: python3 ~/service_control.py enable packagekit")
return
enable_target(sys.argv[2].lower().strip())
else:
print(f"Unknown command: '{action}'")
print_help()
if __name__ == "__main__":
main()
5. Taking Speed Further: Compiling Apps with x86-64-v4 & AVX-512 on Fedora
Once you have freed up RAM and uncapped your CPU with python3 ~/service_control.py uncap, you might notice one more bottleneck: generic binary compilation.
Official Fedora RPM packages are compiled against the baseline x86-64 instruction set (dating back to 2003) so that a single binary runs on every 64-bit processor ever built. That means your modern processor's 512-bit SIMD vector engines (AVX-512) sit completely idle in most standard packages.
Step 1: Verify Your CPU Supports x86-64-v4
x86-64-v4 is the microarchitecture feature level that mandates AVX-512F, AVX-512BW, AVX-512CD, AVX-512DQ, and AVX-512VL (supported on AMD Zen 4 / Zen 5 Ryzen 7000/8000/9000 series and Intel 10th/11th Gen Ice Lake / Tiger Lake & Xeon Scalable CPUs).
Check support directly via Fedora's dynamic linker:
/lib64/ld-linux-x86-64.so.2 --help | grep x86-64-v
If you see x86-64-v4 (supported, searched) in the output, your CPU is ready.
Step 2: Download Source & Compile with x86-64-v4 Optimizations
You have two clean ways to build optimized binaries on Fedora:
Option A: Rebuilding a Fedora Source RPM (rpmbuild)
Ideal for system tools, libraries, ffmpeg, zstd, or Python interpreters:
# 1. Install Fedora RPM build tools and C/C++ compilers
sudo dnf install -y fedora-packager rpmdevtools gcc gcc-c++ clang make cmake
# 2. Set up the rpmbuild directory tree in ~/rpmbuild
rpmdev-setuptree
# 3. Download the source RPM for your target package (example: zstd)
dnf download --source zstd
# 4. Install its build dependencies and unpack the source
sudo dnf builddep -y zstd-*.src.rpm
rpm -ivh zstd-*.src.rpm
# 5. Build with x86-64-v4 + AVX-512 flags injected into RPM optflags
rpmbuild -ba ~/rpmbuild/SPECS/zstd.spec \
--define "optflags -O3 -march=x86-64-v4 -mtune=native -pipe"
Your newly compiled, AVX-512-accelerated RPMs will be waiting in ~/rpmbuild/RPMS/x86_64/, ready to install with sudo dnf reinstall ~/rpmbuild/RPMS/x86_64/*.rpm.
Option B: Compiling Upstream C/C++ Projects Directly
For local AI engines (llama.cpp), media encoders, or scientific tools:
git clone [https://github.com/ggml-org/llama.cpp.git](https://github.com/ggml-org/llama.cpp.git)
cd llama.cpp
cmake -B build \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_C_FLAGS="-O3 -march=x86-64-v4 -mtune=native" \
-DCMAKE_CXX_FLAGS="-O3 -march=x86-64-v4 -mtune=native"
cmake --build build -j$(nproc)
6. Pros & Cons of x86-64-v4 / AVX-512 Compilation
Before recompiling your entire system, weigh where it actually shines versus where it hurts:
Pros
-
Massive Speedups in Vectorized Workloads (15% – 50%+): Video transcoding (
FFmpeg/x265), local LLM CPU inference (llama.cpp), scientific math (NumPy/OpenBLAS), image processing, andzstdcompression process 512 bits of data per clock cycle instead of 128 or 256 bits. -
Double the Vector Registers:
x86-64-v4unlocks 32 wideZMMregisters (up from 16YMMregisters in AVX2), drastically reducing register spills to RAM inside tight loops. - Zero Runtime Dispatch Overhead: Many upstream binaries rely on runtime CPU feature detection; compiling natively eliminates branching overhead.
Cons
-
AVX-512 Frequency Downclocking & Heat (Intel Laptops): On Intel 10th/11th Gen laptops, heavy sustained 512-bit instructions draw significant current, causing the CPU to lower its all-core boost clock and ramp up fans. (Note: AMD Zen 4 and Zen 5 CPUs execute AVX-512 without severe clock penalties, making
x86-64-v4a pure win on modern Ryzen laptops). -
Zero Binary Portability: A binary compiled with
-march=x86-64-v4will immediately crash withSIGILL (Illegal instruction)if copied to an older PC or a standard cloud VM that lacks AVX-512. -
Minimal Gains for General UI/Web Apps: Browsers, file managers, and text editors are bottlenecked by memory latency, network I/O, and GPU compositing—not SIMD math. Save
x86-64-v4compilation for compute-heavy tools rather than wasting hours recompiling your desktop environment. - Manual Update Maintenance: Custom-compiled RPMs or binaries won't automatically receive DNF security patches unless you rebuild them when upstream updates drop.
Wrapping Up
Combining service masking, ZRAM-aware kernel tuning, on-demand TuneD uncapping, and targeted x86-64-v4 compilation turns Fedora into a lean, ultra-responsive workstation without sacrificing stability—and everything remains 100% reversible with a single command.
If you have other Fedora services or kernel sysctl tweaks in your daily toolkit, drop them in the comments!
來源:DEV Community · dev.to
