Digital input (GPIO.input) in Raspberry Pi - Time & Space Complexity
When reading a digital input on a Raspberry Pi, it is important to understand how the time to read changes as you do more reads.
We want to know how the time grows when we read the input many times.
Analyze the time complexity of the following code snippet.
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
for i in range(n):
value = GPIO.input(17)
print(value)
This code reads the digital input from pin 17 on the Raspberry Pi n times and prints the value each time.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading the digital input using
GPIO.input(17). - How many times: This operation repeats exactly n times inside the loop.
Each time we increase n, the number of reads grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads |
| 100 | 100 reads |
| 1000 | 1000 reads |
Pattern observation: The total work grows in a straight line as n increases.
Time Complexity: O(n)
This means the time to complete the reads grows directly in proportion to how many times you read the input.
[X] Wrong: "Reading the input once or many times takes the same amount of time overall."
[OK] Correct: Each read takes some time, so doing it many times adds up and takes longer.
Understanding how repeated hardware reads affect performance helps you write efficient code for real devices and shows you can think about how programs scale.
"What if we added a delay inside the loop after each read? How would the time complexity change?"