GPIO cleanup on exit in Raspberry Pi - Time & Space Complexity
When working with Raspberry Pi GPIO pins, cleaning up on exit is important to reset pin states. We want to understand how the time to clean up changes as the number of pins used grows.
How does the cleanup process scale when more pins are involved?
Analyze the time complexity of the following GPIO cleanup code.
import RPi.GPIO as GPIO
pins = [17, 18, 27, 22, 23]
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
# Later, on program exit
for pin in pins:
GPIO.cleanup(pin)
This code sets up several pins as outputs, then cleans up each pin individually when the program ends.
- Primary operation: Looping through the list of pins to clean each one.
- How many times: Once for each pin in the list.
Each pin requires one cleanup call, so the total work grows as the number of pins increases.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 cleanup calls |
| 50 | 50 cleanup calls |
| 500 | 500 cleanup calls |
Pattern observation: The cleanup time grows directly with the number of pins.
Time Complexity: O(n)
This means the cleanup time increases in a straight line as you add more pins to clean.
[X] Wrong: "Cleaning up all pins takes the same time no matter how many pins are used."
[OK] Correct: Each pin cleanup is a separate action, so more pins mean more cleanup steps and more time.
Understanding how cleanup scales helps you write reliable Raspberry Pi programs that manage resources well. This skill shows you think about program behavior beyond just making it work.
"What if we used a single GPIO.cleanup() call without specifying pins? How would the time complexity change?"