|
| 1 | +""" |
| 2 | +CPU Saver - Automatic Background App Limiter |
| 3 | +
|
| 4 | +This example automatically saves CPU by limiting background applications when they |
| 5 | +become inactive. It gives full priority to whatever application you're currently using |
| 6 | +while throttling everything else that's running in the background. |
| 7 | +
|
| 8 | +Perfect for: |
| 9 | +- Gaming (limit background apps while gaming) |
| 10 | +- Work (focus CPU on your active application) |
| 11 | +- Battery saving (reduce overall system load) |
| 12 | +- Performance optimization |
| 13 | +
|
| 14 | +Requirements: |
| 15 | +- Administrator privileges (the script will try to restart itself with admin rights) |
| 16 | +- cpulimiter library: pip install cpulimiter |
| 17 | +""" |
| 18 | + |
| 19 | +import sys |
| 20 | +import ctypes |
| 21 | +import time |
| 22 | +from cpulimiter import CpuLimiter, get_active_app_pids, get_active_window_info |
| 23 | + |
| 24 | +# --- CONFIGURATION --- |
| 25 | +# How much to limit the CPU by (98 = limit by 98%, leaving 2% for the app) |
| 26 | +LIMIT_PERCENTAGE = 98 |
| 27 | + |
| 28 | +# How many seconds of inactivity before an app is limited |
| 29 | +INACTIVITY_THRESHOLD_SECONDS = 10 |
| 30 | + |
| 31 | +# How often the script checks for active/inactive apps (in seconds) |
| 32 | +LOOP_INTERVAL_SECONDS = 5 |
| 33 | + |
| 34 | +# List of process names to ignore (critical system processes and tools) |
| 35 | +IGNORE_LIST = { |
| 36 | + "explorer.exe", # Windows Explorer (taskbar, etc.) |
| 37 | + "svchost.exe", # Critical Windows service host |
| 38 | + "powershell.exe", # PowerShell console |
| 39 | + "cmd.exe", # Command prompt |
| 40 | + "WindowsTerminal.exe", # Windows Terminal |
| 41 | + "python.exe", # Python interpreter |
| 42 | + "conhost.exe", # Console Window Host |
| 43 | + "dwm.exe", # Desktop Window Manager |
| 44 | + "winlogon.exe", # Windows Logon Process |
| 45 | + "csrss.exe", # Client/Server Runtime |
| 46 | +} |
| 47 | + |
| 48 | +def is_admin(): |
| 49 | + """Checks if the script is running with Administrator privileges.""" |
| 50 | + try: |
| 51 | + return ctypes.windll.shell32.IsUserAnAdmin() |
| 52 | + except: |
| 53 | + return False |
| 54 | + |
| 55 | +def main(): |
| 56 | + """Main loop to monitor and save CPU automatically.""" |
| 57 | + print("💾 CPU Saver Started!") |
| 58 | + print(f"⚡ Limiting background apps by {LIMIT_PERCENTAGE}% after {INACTIVITY_THRESHOLD_SECONDS} seconds of inactivity") |
| 59 | + print(f"🛡️ Protected system processes: {len(IGNORE_LIST)} processes") |
| 60 | + print("⌨️ Press Ctrl+C to stop\n") |
| 61 | + |
| 62 | + # Initialize the limiter |
| 63 | + limiter = CpuLimiter() |
| 64 | + last_active_time = {} |
| 65 | + limited_pids = set() |
| 66 | + |
| 67 | + try: |
| 68 | + while True: |
| 69 | + current_time = time.time() |
| 70 | + |
| 71 | + # Get current state |
| 72 | + visible_apps = get_active_app_pids() |
| 73 | + active_window = get_active_window_info() |
| 74 | + active_pid = active_window['pid'] if active_window else None |
| 75 | + |
| 76 | + # Update last active time for the currently active app |
| 77 | + if active_pid: |
| 78 | + last_active_time[active_pid] = current_time |
| 79 | + |
| 80 | + # Check each visible app |
| 81 | + for pid, app_info in visible_apps.items(): |
| 82 | + app_name = app_info['name'] |
| 83 | + |
| 84 | + # Skip apps in ignore list (critical system processes) |
| 85 | + if app_name in IGNORE_LIST: |
| 86 | + continue |
| 87 | + |
| 88 | + is_currently_active = (pid == active_pid) |
| 89 | + is_currently_limited = pid in limited_pids |
| 90 | + |
| 91 | + # Determine if we should limit this app |
| 92 | + if not is_currently_active and not is_currently_limited: |
| 93 | + time_since_active = current_time - last_active_time.get(pid, 0) |
| 94 | + |
| 95 | + if time_since_active > INACTIVITY_THRESHOLD_SECONDS: |
| 96 | + print(f"🔒 Saving CPU: Limiting {app_name} (PID: {pid})") |
| 97 | + limiter.add(pid=pid, limit_percentage=LIMIT_PERCENTAGE) |
| 98 | + limiter.start(pid=pid) |
| 99 | + limited_pids.add(pid) |
| 100 | + |
| 101 | + # Remove limit if app becomes active |
| 102 | + elif is_currently_active and is_currently_limited: |
| 103 | + print(f"🔓 Restoring speed: Unlimiting {app_name} (PID: {pid})") |
| 104 | + limiter.stop(pid=pid) |
| 105 | + limited_pids.discard(pid) |
| 106 | + |
| 107 | + # Clean up limiters for apps that are no longer visible |
| 108 | + pids_to_remove = [] |
| 109 | + for pid in limited_pids: |
| 110 | + if pid not in visible_apps: |
| 111 | + print(f"🧹 Cleaning up limiter for closed app (PID: {pid})") |
| 112 | + limiter.stop(pid=pid) |
| 113 | + pids_to_remove.append(pid) |
| 114 | + |
| 115 | + for pid in pids_to_remove: |
| 116 | + limited_pids.discard(pid) |
| 117 | + |
| 118 | + # Status update every 30 seconds |
| 119 | + if int(current_time) % 30 == 0 and limited_pids: |
| 120 | + limited_apps = [visible_apps.get(pid, {}).get('name', 'Unknown') for pid in limited_pids] |
| 121 | + print(f"📊 CPU Savings: {len(limited_pids)} background apps limited: {', '.join(limited_apps)}") |
| 122 | + |
| 123 | + # Wait before next check |
| 124 | + time.sleep(LOOP_INTERVAL_SECONDS) |
| 125 | + |
| 126 | + except KeyboardInterrupt: |
| 127 | + print("\n⚠️ CPU Saver stopped by user") |
| 128 | + |
| 129 | + finally: |
| 130 | + print("🧹 Restoring all apps to full speed...") |
| 131 | + limiter.stop_all() |
| 132 | + print("✅ CPU Saver stopped cleanly") |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + # Check for admin privileges |
| 136 | + if not is_admin(): |
| 137 | + print("🔐 Administrator privileges required for CPU Saver") |
| 138 | + print("🔄 Attempting to restart with elevated privileges...") |
| 139 | + try: |
| 140 | + ctypes.windll.shell32.ShellExecuteW( |
| 141 | + None, "runas", sys.executable, " ".join(sys.argv), None, 1 |
| 142 | + ) |
| 143 | + except Exception as e: |
| 144 | + print(f"❌ Failed to restart with admin privileges: {e}") |
| 145 | + print("💡 Please run this script as Administrator manually") |
| 146 | + sys.exit(1) |
| 147 | + else: |
| 148 | + print("✅ Running with Administrator privileges") |
| 149 | + main() |
0 commit comments