Digital output (GPIO.output) in Raspberry Pi - Time & Space Complexity
When using GPIO.output on a Raspberry Pi, it is helpful to understand how the time to run the code changes as you control more pins.
We want to know how the number of pins affects the total time to set their states.
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
pins = [17, 18, 27, 22]
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.HIGH)
GPIO.cleanup()
This code sets up a list of pins and turns each one on (high) one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of pins to set each pin's output state.
- How many times: Once for each pin in the list.
Each additional pin adds one more GPIO.output call, so the total work grows directly with the number of pins.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 GPIO.output calls |
| 100 | 100 GPIO.output calls |
| 1000 | 1000 GPIO.output calls |
Pattern observation: The time grows steadily and directly with the number of pins controlled.
Time Complexity: O(n)
This means the time to set pin outputs increases in a straight line as you add more pins.
[X] Wrong: "Setting multiple pins at once with GPIO.output is always faster and constant time."
[OK] Correct: Even if you try to set many pins, the code still needs to handle each pin internally, so the time grows with the number of pins.
Understanding how controlling hardware pins scales with the number of pins helps you write efficient code for real devices and shows you can think about performance beyond just software.
"What if we used a single command to set all pins at once? How would the time complexity change?"