Skip to content

Commit bbe8bb2

Browse files
committed
Add examples to README and implement example scripts for CPU limiting
1 parent 736c064 commit bbe8bb2

File tree

4 files changed

+418
-0
lines changed

4 files changed

+418
-0
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,15 @@ limiter.stop(process_name="chrome.exe")
4343
print("Process limit removed.")
4444
```
4545

46+
## Examples 📚
47+
48+
Check out the `examples/` folder for different use cases:
49+
50+
- **`basic_usage.py`** - Simple introduction to the library
51+
- **`simple_limit.py`** - Manually limit specific applications
52+
- **`cpu_saver.py`** - Automatic CPU saver that limits all background apps
53+
- **`advanced_interactive.py`** - Interactive mode with real-time control
54+
4655
## API Reference
4756

4857
### `CpuLimiter` Class

examples/advanced_interactive.py

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
"""
2+
Advanced CPU Limiter Example
3+
4+
This example demonstrates advanced features of the cpulimiter library:
5+
- Targeting processes by different methods (PID, name, window title)
6+
- Individual process control
7+
- Real-time monitoring and adjustment
8+
- Dynamic process discovery
9+
"""
10+
11+
from cpulimiter import CpuLimiter, get_active_app_pids, get_active_window_info
12+
import time
13+
import sys
14+
15+
def show_available_apps():
16+
"""Display all currently running applications with visible windows."""
17+
print("🔍 Scanning for running applications...")
18+
apps = get_active_app_pids()
19+
20+
if not apps:
21+
print("❌ No applications with visible windows found")
22+
return
23+
24+
print(f"📱 Found {len(apps)} applications:")
25+
print("-" * 50)
26+
for pid, info in apps.items():
27+
print(f" PID: {pid:6} | {info['name']:20} | {info['title'][:30]}...")
28+
print("-" * 50)
29+
30+
def interactive_limiting():
31+
"""Interactive mode where user can select applications to limit."""
32+
limiter = CpuLimiter()
33+
34+
while True:
35+
print("\n🎛️ INTERACTIVE CPU LIMITER")
36+
print("1. 📋 Show running applications")
37+
print("2. 🎯 Limit application by name")
38+
print("3. 🔢 Limit application by PID")
39+
print("4. 🖼️ Limit by window title (contains)")
40+
print("5. 📊 Show current limits")
41+
print("6. 🛑 Stop specific limit")
42+
print("7. 🛑 Stop all limits")
43+
print("8. 🚪 Exit")
44+
45+
choice = input("\nSelect option (1-8): ").strip()
46+
47+
if choice == "1":
48+
show_available_apps()
49+
50+
elif choice == "2":
51+
name = input("Enter process name (e.g., chrome.exe): ").strip()
52+
if name:
53+
try:
54+
limit = int(input("Enter limit percentage (1-99): "))
55+
limiter.add(process_name=name, limit_percentage=limit)
56+
limiter.start(process_name=name)
57+
print(f"✅ Started limiting {name} by {limit}%")
58+
except ValueError:
59+
print("❌ Invalid percentage")
60+
61+
elif choice == "3":
62+
try:
63+
pid = int(input("Enter PID: "))
64+
limit = int(input("Enter limit percentage (1-99): "))
65+
limiter.add(pid=pid, limit_percentage=limit)
66+
limiter.start(pid=pid)
67+
print(f"✅ Started limiting PID {pid} by {limit}%")
68+
except ValueError:
69+
print("❌ Invalid PID or percentage")
70+
71+
elif choice == "4":
72+
title = input("Enter window title substring: ").strip()
73+
if title:
74+
try:
75+
limit = int(input("Enter limit percentage (1-99): "))
76+
limiter.add(window_title_contains=title, limit_percentage=limit)
77+
limiter.start(window_title_contains=title)
78+
print(f"✅ Started limiting windows containing '{title}' by {limit}%")
79+
except ValueError:
80+
print("❌ Invalid percentage")
81+
82+
elif choice == "5":
83+
active = limiter.get_active()
84+
if active:
85+
print(f"\n📊 Currently limiting {len(active)} processes:")
86+
for proc in active:
87+
print(f" - PID: {proc['pid']}, Limit: {proc['limit_percentage']}%")
88+
else:
89+
print("📊 No processes currently being limited")
90+
91+
elif choice == "6":
92+
method = input("Stop by (name/pid): ").strip().lower()
93+
if method == "name":
94+
name = input("Enter process name: ").strip()
95+
limiter.stop(process_name=name)
96+
print(f"🛑 Stopped limiting {name}")
97+
elif method == "pid":
98+
try:
99+
pid = int(input("Enter PID: "))
100+
limiter.stop(pid=pid)
101+
print(f"🛑 Stopped limiting PID {pid}")
102+
except ValueError:
103+
print("❌ Invalid PID")
104+
105+
elif choice == "7":
106+
limiter.stop_all()
107+
print("🛑 Stopped all limits")
108+
109+
elif choice == "8":
110+
limiter.stop_all()
111+
print("👋 Goodbye!")
112+
break
113+
114+
else:
115+
print("❌ Invalid choice")
116+
117+
def auto_monitor_mode():
118+
"""Automatically monitor and display the currently active application."""
119+
print("🔄 AUTO-MONITOR MODE")
120+
print("This mode will show you which application is currently active")
121+
print("Press Ctrl+C to return to main menu\n")
122+
123+
try:
124+
while True:
125+
active = get_active_window_info()
126+
if active:
127+
print(f"🎯 Active: {active['name']} (PID: {active['pid']}) - {active['title'][:50]}...")
128+
else:
129+
print("❓ No active window detected")
130+
time.sleep(2)
131+
except KeyboardInterrupt:
132+
print("\n🔙 Returning to main menu...")
133+
134+
def main():
135+
print("🚀 ADVANCED CPU LIMITER")
136+
print("=" * 50)
137+
138+
while True:
139+
print("\n🎛️ MAIN MENU")
140+
print("1. 🎮 Interactive Limiting Mode")
141+
print("2. 👁️ Auto-Monitor Mode (see active apps)")
142+
print("3. 📋 Quick App List")
143+
print("4. 🚪 Exit")
144+
145+
choice = input("\nSelect mode (1-4): ").strip()
146+
147+
if choice == "1":
148+
interactive_limiting()
149+
elif choice == "2":
150+
auto_monitor_mode()
151+
elif choice == "3":
152+
show_available_apps()
153+
elif choice == "4":
154+
print("👋 Goodbye!")
155+
break
156+
else:
157+
print("❌ Invalid choice")
158+
159+
if __name__ == "__main__":
160+
import ctypes
161+
162+
# Check for admin privileges
163+
try:
164+
is_admin = ctypes.windll.shell32.IsUserAnAdmin()
165+
except:
166+
is_admin = False
167+
168+
if not is_admin:
169+
print("🔐 Administrator privileges required")
170+
print("🔄 Please run as Administrator")
171+
input("Press Enter to exit...")
172+
sys.exit(1)
173+
174+
try:
175+
main()
176+
except KeyboardInterrupt:
177+
print("\n\n🛑 Program interrupted by user")
178+
except Exception as e:
179+
print(f"\n❌ An error occurred: {e}")
180+
input("Press Enter to exit...")

examples/cpu_saver.py

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
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

Comments
 (0)