DistanceSensor (ultrasonic) in Raspberry Pi - Time & Space Complexity
When using an ultrasonic DistanceSensor on a Raspberry Pi, it's important to understand how the time to get distance readings grows as we take more measurements.
We want to know how the program's running time changes when we increase the number of distance checks.
Analyze the time complexity of the following code snippet.
from gpiozero import DistanceSensor
sensor = DistanceSensor(echo=17, trigger=4)
for i in range(n):
distance = sensor.distance
print(f"Distance {i+1}: {distance:.2f} meters")
This code takes n distance measurements from the ultrasonic sensor and prints each result.
- Primary operation: Reading the distance from the sensor inside the loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each additional measurement adds one more sensor reading and print operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sensor reads + 10 prints |
| 100 | 100 sensor reads + 100 prints |
| 1000 | 1000 sensor reads + 1000 prints |
Pattern observation: The total work grows directly in proportion to the number of measurements.
Time Complexity: O(n)
This means the time to complete the program grows linearly as you increase the number of distance readings.
[X] Wrong: "Reading the sensor once and printing multiple times is the same as reading it multiple times."
[OK] Correct: Each sensor reading takes time and reflects a new measurement; printing multiple times without new readings does not give updated distances.
Understanding how loops affect program time helps you explain how sensor data collection scales, a useful skill when working with hardware and real-time data.
"What if we added a delay inside the loop between readings? How would the time complexity change?"