Last active
June 29, 2026 10:16
-
-
Save davidechicco/e6506d569209427a5ddbe9ed81b40468 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # | |
| # Code snippet written by Davide Chicco <davidechicco@davidechicco.it> on 25th March 2026 | |
| # Tested on Linux Xubuntu 24.04.4 LTS with Python 3.11.9 | |
| # | |
| import subprocess | |
| import sys | |
| import time # <-- Added for timing | |
| # --- Upgrade pip --- | |
| bash_command = sys.executable + " -m pip install --upgrade pip" | |
| print("bash_command:\n", bash_command) | |
| result = subprocess.run(bash_command, shell=True, capture_output=True, text=True) | |
| # --- Ensure CodeCarbon is installed --- | |
| libraries = ["codecarbon"] | |
| for lib in libraries: | |
| try: | |
| __import__(lib) | |
| print(f"{lib} is already installed.") | |
| except ImportError: | |
| print(f"{lib} not found. Installing...") | |
| subprocess.check_call([sys.executable, "-m", "pip", "install", lib]) | |
| print("output:\t", result.stdout) | |
| if result.stderr: | |
| print("errors:\t", result.stderr) | |
| # --- Import after install --- | |
| from codecarbon import EmissionsTracker | |
| # ========================= | |
| # Run your software code | |
| # ========================= | |
| tracker = EmissionsTracker( | |
| log_level="error", | |
| save_to_file=False | |
| ) | |
| tracker.start() | |
| # --- Measure execution time --- | |
| start_time = time.time() | |
| # | |
| # (Insert your original Python code here) | |
| # | |
| end_time = time.time() | |
| execution_time = end_time - start_time | |
| emissions = tracker.stop() * 1000 | |
| energy_wh = tracker._total_energy.kWh * 1000 | |
| print(f"\n~ : ~ consumption measured through CodeCarbon ~ : ~") | |
| print(f"Python energy: {energy_wh:.20f} Wh") | |
| print(f"Python emissions: {emissions:.20f} CO\u2082eq grams") | |
| print(f"Python execution time: {execution_time:.20f} seconds") | |
| print(f"~ : ~ : ~ : ~ : ~ : ~ : ~") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment