DEV Community

Vladislav Radchenko
Vladislav Radchenko

Posted on

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

How can we save the planet in other programming languages? Let's discuss!

Top comments (3)

Collapse
 
oliverbennet profile image
Oliver Bennet

Thanks, let's use the platform better

Collapse
 
radchenko profile image
Vladislav Radchenko

I agree with you 🤝

Collapse
 
codepicker profile image
CodePicker

very useful