Grade by Grade
D. Topics in Computer Science · Topics in Computer Science: Sustainability, Ethics, Emerging Technologies and Careers

Green Software: Writing Code That Uses Less Energy

D1.1About 70 minutes
Learning goals
  • I can explain three levers programmers control: energy efficiency, carbon awareness and hardware efficiency.
  • I can connect algorithm efficiency to energy use by counting operations.
  • I can write a program that finds the lowest-carbon time window for a flexible job.
  • I can identify trade-offs between greener choices and other goals.

Words to know

energy efficiency (software)
Getting the same result with less computation, data movement or machine time.
carbon-aware computing
Running flexible work at the times or places where electricity has the lowest emissions.
hardware efficiency
Making the most of existing hardware so that less new hardware has to be made.
flexible job
Computing work whose timing can change without harming users, such as backups and updates.
cache
A store of results or downloaded data kept so it can be reused instead of recomputed or downloaded again.
sliding window
A technique that examines each run of consecutive values of a fixed length in turn.

Software decides how hard the hardware works

In the last lesson the numbers showed that the hardware itself carries most of the footprint. But software decides how many processor cycles are used, how much data crosses the network, how long a server stays busy, and whether an old laptop can still run the latest version of an app. Programmers make environmental decisions every time they choose an algorithm.

This lesson gives you three levers you control as a programmer.

Three levers for greener softwareEnergy efficiencyDo the same workwith less computation:better algorithms,less data movedCarbon awarenessRun flexible jobswhen and where theelectricity is cleanestHardware efficiencyMake software that runswell on older devices,so hardware lasts longer
The three levers. Each one reduces a different part of the footprint you met in The Full Footprint of Computing.

Lever 1: Energy efficiency

A processor uses energy for every operation. If two programs give the same answer, the one that does fewer operations usually uses less energy. That is why the analysis you do in the unit Algorithm Design and Analysis (counting comparisons, comparing linear and binary search) is also an environmental skill.

Other energy savers:

  • Move less data. Sending data across networks and storing it in data centres uses energy. Compress images, don't download what you won't show, and avoid checking a server every second when once a minute will do.
  • Cache results you will need again instead of recomputing or re-downloading them.
  • Don't keep machines busy for nothing: stop test servers and cloud machines when they are not in use.
def linear_count(items, target):
count = 0
for x in items:
count += 1
if x == target:
break
return count
def binary_count(items, target):
lo, hi, count = 0, len(items) - 1, 0
while lo <= hi:
count += 1
mid = (lo + hi) // 2
if items[mid] == target:
break
elif items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return count
data = list(range(1_000_000))
for t in [10, 500_000, 999_999]:
print(t, linear_count(data, t), binary_count(data, t))

Counting comparisons (loop iterations) for both searches on a sorted list of one million numbers. Each line shows the target, the linear count and the binary count.

10 11 18
500000 500001 19
999999 1000000 20

Output of the program above (what Python prints).

For the last target, linear search does a million comparisons and binary search does 20. If the search runs millions of times a day on a server, that difference becomes real electricity. (Binary search needs sorted data; sorting costs work too, so it pays off when you search the same data many times.)

Lever 2: Carbon awareness

Grid intensity changes during the day. In many grids, including Ontario's, natural-gas plants are turned up to meet peak demand, so a kWh used at 6 p.m. can carry more CO2e than one used at 3 a.m. Some work is flexible: backups, software updates, training a machine-learning model, rendering video. A carbon-aware program schedules flexible work for the cleanest hours, or in a data-centre region with a cleaner grid.

Grid operators and some online services publish current and forecast intensity. The program below uses made-up practice values to find the best three-hour window.

Grid intensity through one day (made-up practice values, g CO2e/kWh)0:003:006:009:0012:0015:0018:0021:00best 3-hour window(3:00 to 6:00)evening peakhour of the day
Made-up hourly intensities for practice. The highlighted bars (green) are the three-hour window with the lowest total.
intensity = [42, 40, 38, 36, 35, 36, 45, 60, 75, 80, 78, 70,
65, 62, 64, 70, 82, 95, 98, 90, 75, 60, 50, 45]
def best_window(values, length):
best_start = 0
best_total = sum(values[0:length])
for start in range(1, len(values) - length + 1):
total = sum(values[start:start + length])
if total < best_total:
best_start, best_total = start, total
return best_start, best_total
start, total = best_window(intensity, 3)
print("Start at", str(start) + ":00, average", round(total / 3, 1), "g/kWh")
peak, ptotal = 17, sum(intensity[17:20])
print("Peak window 17:00 average", round(ptotal / 3, 1), "g/kWh")

A sliding-window search: try every start hour and keep the lowest total.

Start at 3:00, average 35.7 g/kWh
Peak window 17:00 average 94.3 g/kWh

Output of the program above (what Python prints).

Worked example

Example 1: Is rescheduling worth it?

A nightly job runs on 4 servers that each draw 300 W, for 3 hours. Compare its emissions if it runs in the 3:00 window (average 35.7 g/kWh) or the 17:00 peak window (average 94.3 g/kWh), using the values above.

  1. Energy: 4 × 300 W × 3 h = 3600 Wh = 3.6 kWh per night (the same either way).
  2. Off-peak: 3.6 × 35.7 ≈ 128.5 g CO2e per night.
  3. Peak: 3.6 × 94.3 ≈ 339.5 g CO2e per night.
  4. Difference ≈ 211 g per night, or about 211 × 365 ≈ 77 000 g ≈ 77 kg per year for one small job.
  5. The energy did not change at all; only the timing did.

Running off-peak cuts this job's emissions by about 62% (211 ÷ 339.5), about 77 kg CO2e per year, with no change to the code's work.

Lever 3: Hardware efficiency

When an app or website grows so heavy that only new phones can run it smoothly, people replace working devices. Software that stays lightweight and keeps supporting older devices and operating systems lets hardware last longer, which is the biggest lever from the last lesson. Practical habits:

  • test your program on an older or slower machine;
  • avoid adding large libraries for one small feature;
  • keep supporting older versions of an operating system when it is safe to do so (security updates still matter);
  • use the hardware you have fully, for example by sharing one server between several small services instead of running several half-empty ones.

Trade-offs are real

Greener choices sometimes compete with other goals. Caching saves energy but uses memory and can show out-of-date data. Supporting old devices takes extra testing time. Delaying a job saves carbon but the result arrives later. Good engineers state the trade-off openly and choose deliberately.

Just for fun

Why did the programmer's app get so fast after she stopped asking the server the same question every second?

She finally learned to cache in on her savings.

Hands-on activity

Measure it yourself

You need: a computer with Python.

  1. Run the program below. It times 2000 membership tests in a list and in a set of 100 000 numbers. (Times vary from computer to computer, so the program only prints which is faster.)
  2. Change it to print the two times with print(round(t_list, 4), round(t_set, 4)) and run it three times. Record the times.
  3. Explain the difference: a list checks items one by one (like linear search); a set jumps almost straight to the item using hashing.
  4. Write two sentences on what this means for energy if the check runs a billion times a day on a server.

What to look for: times recorded in a table, the set being much faster each time, and an explanation that fewer operations means less processor time and less energy.

import time
nums_list = list(range(100_000))
nums_set = set(nums_list)
tests = range(99_000, 101_000)
t0 = time.perf_counter()
hits_list = sum(1 for t in tests if t in nums_list)
t_list = time.perf_counter() - t0
t0 = time.perf_counter()
hits_set = sum(1 for t in tests if t in nums_set)
t_set = time.perf_counter() - t0
print("Same answer:", hits_list == hits_set, hits_list)
print("Set lookup faster:", t_set < t_list)

For the activity. time.perf_counter() reads a precise clock; the difference of two readings is the elapsed time in seconds.

Same answer: True 1000
Set lookup faster: True

Output of the program above (what Python prints).

Your turn

1

Name the three levers for greener software and give one example of each.

2

Linear search on a sorted list of 1 000 000 items looks for the last item. How many comparisons does it make? About how many does binary search make?

3

What is a flexible computing job? Give two examples.

4

A job uses 2 kWh. How many grams of CO2e does it release at 40 g/kWh and at 90 g/kWh?

5

Why can a heavy app increase e-waste?

6

What does caching save, and what can it cost?

More practice: warm-up

1

True or false: two programs that give the same answer always use the same energy.

2

What does best_window(intensity, 3) return for the practice data?

3

What does carbon-aware scheduling change: the amount of energy, or the emissions per kWh?

4

Give one way a website can move less data.

5

Why should you stop a cloud test server when you are not using it?

More practice: on your own

1

Using the practice intensities, what is the average for the window starting at 0:00 (hours 0, 1, 2)?

2

A job uses 5 kWh. Moving it from an average of 94.3 g/kWh to 35.7 g/kWh saves how much CO2e per run?

3

Binary search needs sorted data. When is it NOT worth sorting first to use binary search?

4

Modify best_window so it returns the worst (highest) window instead. What one change is needed?

5

A team wants to add a 40 MB library to use one small function. Give an environmental argument against it and a possible alternative.

Challenge

1

Rewrite best_window so it runs in one pass using a running total (add the new hour, subtract the hour that leaves the window) instead of calling sum for every start. Why is this more efficient?

2

A data centre region is 30 g/kWh and another is 500 g/kWh. A company moves a 2000 kWh-per-day training job to the cleaner region but the data must travel further, adding 50 kWh per day of network energy at 100 g/kWh. Is the move worth it? Show the calculation.

3

Explain why 'faster' and 'greener' usually go together for one program, but can disagree when a program is made faster by running it on many more servers at once.

Check your understanding

Quiz

1.

Which change is an example of carbon-aware computing?

2.

A job uses 3 kWh. How much CO2e does it release at 50 g/kWh?

3.

Why can heavy, slow software increase e-waste?

4.

On a sorted list of about 1 000 000 items, about how many comparisons does binary search need at most?

5.

Which statement about caching is accurate?

6.

Moving a flexible job to a cleaner hour changes which quantity?

For parents and teachers

Big idea: This lesson extends expectation D1.1 (strategies to reduce environmental impact) to the programmer's own choices: efficient algorithms, carbon-aware scheduling and lightweight software.

How to help: Ask your teen to explain Example 1 to you: the energy is identical, so why do the emissions change? If you have an older phone or laptop, ask which apps run badly on it and talk about why.

Common difficulties:

  • Confusing energy (kWh) with emissions (g CO2e). Carbon-aware scheduling changes emissions, not energy.
  • Slicing errors in values[start:start + length]: the end index is not included.
  • Assuming faster always means greener. It usually does on one machine, but not when work is spread across many machines.
  • The hourly intensity values in this lesson are made up for practice; real values come from grid operators.