Real-time sensor dashboard in Raspberry Pi - Time & Space Complexity
When building a real-time sensor dashboard on a Raspberry Pi, it's important to understand how the program's speed changes as more sensor data comes in.
We want to know how the time to update the dashboard grows when the number of sensors increases.
Analyze the time complexity of the following code snippet.
while True:
sensor_values = []
for sensor in sensors:
value = sensor.read()
sensor_values.append(value)
display.update(sensor_values)
sleep(1)
This code reads data from each sensor, updates the dashboard display with all values, and repeats every second.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all sensors to read their values.
- How many times: Once every second, the loop runs once over all sensors.
As the number of sensors increases, the time to read and update grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 sensors | 10 reads + 1 update |
| 100 sensors | 100 reads + 1 update |
| 1000 sensors | 1000 reads + 1 update |
Pattern observation: The total work grows directly with the number of sensors.
Time Complexity: O(n)
This means the time to update the dashboard grows in a straight line as you add more sensors.
[X] Wrong: "Reading all sensors happens instantly no matter how many sensors there are."
[OK] Correct: Each sensor read takes time, so more sensors mean more total reading time.
Understanding how your program scales with input size shows you can write efficient code that works well as projects grow.
"What if the dashboard only updated every 5 seconds instead of every second? How would the time complexity change?"