Repository navigation
Day2 Task4
Source: https://github.com/GeoGenetics/data-analysis-2025/tree/main/reproducible-data-analysis/day2/task4
Environment: day2
In this task, we'll dive into practical examples of sustainable software development, demonstrating how coding practices can significantly impact resource use and CO₂ emissions. We utilize CodeCarbon, a Python library, to measure these impacts in real-time.
We will present two explicit examples showcasing inefficient (bad) and optimized (good) coding practices and measure their respective environmental impacts.
This example demonstrates poor coding practices, specifically inefficient loops that cause unnecessary computational load.
from codecarbon import EmissionsTracker
import pandas as pd
# Initialize CodeCarbon tracker
tracker = EmissionsTracker(project_name="Inefficient_Data_Processing")
tracker.start()
# Creating a DataFrame
df = pd.DataFrame({'numbers': range(1, 1000000)})
# Inefficient data processing using loops
sum_total = 0
for i in range(len(df)):
sum_total += df.iloc[i]['numbers'] # Inefficient row-wise access
# Stopping the tracker
tracker.stop()To run the code:
# First we will update the repo by pulling changes
cd ~/course/wdir/data-analysis-2025/reproducible-data-analysis
git pull
then we will go to:
cd ~/course/wdir/data-analysis-2025/reproducible-data-analysis/day2/task4
python bad.py
Issues identified:
- Inefficient looping and row-wise DataFrame access.
- Higher energy consumption leading to increased CO₂ emissions.
- Extended execution time.
This example illustrates optimal coding practices by leveraging vectorized operations, significantly improving efficiency and reducing resource usage.
from codecarbon import EmissionsTracker
import pandas as pd
# Initialize CodeCarbon tracker
tracker = EmissionsTracker(project_name="Efficient_Data_Processing")
tracker.start()
# Creating a DataFrame
df = pd.DataFrame({'numbers': range(1, 1000000)})
# Efficient vectorized computation
sum_total = df['numbers'].sum() # Optimized operation using vectorization
# Stopping the tracker
tracker.stop()To run the code:
cd ~/course/wdir/data-analysis-2025/reproducible-data-analysis/day2/task4
python good.py
Benefits:
- Efficient, vectorized computation.
- Reduced CPU usage, resulting in lower energy consumption.
- Faster execution times.
These detailed examples highlight that even small coding decisions can lead to significant environmental impacts, especially when scaled up to large user bases. Developers can meaningfully contribute to sustainability through thoughtful, optimized coding practices.
Let's check the emissions:
pip install tabview
taview emissions.csv