Logo

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
Categories
4 categories in total
devto
open
discuss
open
jokes
open
python
open
Automate Saving the Planet... Or Just Your Computer's Energy ๐Ÿ

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!

Featured ones: