Setting pin mode (IN, OUT) in Raspberry Pi - Time & Space Complexity
When we set a pin mode on a Raspberry Pi, we want to know how long it takes as we do it many times.
We ask: How does the time grow when we set modes for more pins?
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
pins = [2, 3, 4, 5, 6]
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
This code sets the mode of each pin in a list to output mode one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Setting pin mode using
GPIO.setupinside a loop. - How many times: Once for each pin in the list.
Each pin requires one setup call, so the total work grows as the number of pins grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 setup calls |
| 100 | 100 setup calls |
| 1000 | 1000 setup calls |
Pattern observation: The time grows directly with the number of pins.
Time Complexity: O(n)
This means if you double the number of pins, the time to set them doubles too.
[X] Wrong: "Setting pin modes happens instantly no matter how many pins there are."
[OK] Correct: Each pin requires a separate command, so more pins mean more time.
Understanding how setting pin modes scales helps you write efficient hardware control code and shows you can think about performance in real projects.
"What if we set all pins to input mode instead of output? How would the time complexity change?"