dev-resources.site
for different kinds of informations.
Automate Saving the Planet... Or Just Your Computer's Energy ๐
Published at
11/19/2024
Categories
devto
discuss
jokes
python
Author
Wladislav Radchenko
I came across @oliverbennet is post "What's a Quickie Post?" and couldnโt resist giving it a try Quickie Post myself. So, hereโs a Python twist on a global problem:
Problem: Fighting climate change is a serious challenge, but did you know Python is playing a role in it?
Imagine youโre writing code on Python to help reduce energy waste:
import os
def save_energy():
if os.name == "nt": # Windows
os.system("shutdown /s /t 1")
elif os.name == "posix": # macOS/Linux
os.system("pmset sleepnow")
else:
print("Unsupported OS! ๐๐ป")
print("Computer shutting down to save energy! ๐ฑ")
# Save the planet
save_energy()
Great, let's try something more sophisticated. Weโre all aware that high CPU or GPU usage translates to more energy consumption. So, this Python script uses APScheduler to periodically check system load, and if itโs too high, it shuts down or puts the computer to sleep. ๐
import os
import psutil # For monitoring CPU usage
import GPUtil # For monitoring GPU usage
from apscheduler.schedulers.blocking import BlockingScheduler
def save_energy():
"""Shutdown or put the system to sleep if CPU or GPU load is too high."""
print("Energy-saving monitor started! ๐ฟ")
if os.name == "nt": # Windows
os.system("shutdown /s /t 1")
elif os.name == "posix": # macOS/Linux
os.system("pmset sleepnow")
else:
print("Unsupported OS! ๐๐ป")
print("Computer shutting down to save energy! ๐ฑ")
def check_system_load():
"""Check CPU and GPU load and trigger save_energy if either is too high."""
# Check CPU load
cpu_load = psutil.cpu_percent(interval=1)
print(f"Current CPU Load: {cpu_load}%")
# Check GPU load
gpus = GPUtil.getGPUs()
if gpus:
gpu_load = max(gpu.load * 100 for gpu in gpus) # Get max load of all GPUs
print(f"Current GPU Load: {gpu_load}%")
else:
gpu_load = 0
print("No GPUs detected.")
# Trigger energy-saving if CPU or GPU load is too high
if cpu_load > 90 or gpu_load > 90: # Adjust thresholds as needed
print("High system load detected! Initiating energy-saving protocol... ๐จ")
save_energy()
# Set up the scheduler
scheduler = BlockingScheduler()
scheduler.add_job(check_system_load, 'interval', minutes=1) # Check every minute
How can we save the planet in other programming languages? Let's discuss!
Articles
7 articles in total
Your coding year in review
read article
DevHunt Weekly: Unfair Rankings or Just a Glitch?
read article
Automate Saving the Planet... Or Just Your Computer's Energy ๐
currently reading
Exploring dev.to's Hidden Features: Upload a Video. What?
read article
[ROAST] Launching on DevHunt Doesn't Work? Here's What I Found!
read article
Practical Experience: Integrating Over 50 Neural Networks Into One Open-Source Project
read article
My Journey to dream: 4096 โญ on GitHub
read article
Featured ones: