Publishing sensor data in Raspberry Pi - Time & Space Complexity
When publishing sensor data on a Raspberry Pi, it is important to understand how the time taken grows as more data is sent.
We want to know how the program's work changes when the number of sensor readings increases.
Analyze the time complexity of the following code snippet.
import time
sensor_data = [23, 25, 22, 24, 26] # example sensor readings
def publish_data(data):
for reading in data:
send_to_server(reading) # sends one reading
time.sleep(0.1) # wait to avoid flooding
publish_data(sensor_data)
This code sends each sensor reading one by one to a server, pausing briefly between sends.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each sensor reading to send it.
- How many times: Once for each reading in the data list.
As the number of sensor readings grows, the total sending time grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sends and waits |
| 100 | 100 sends and waits |
| 1000 | 1000 sends and waits |
Pattern observation: The work grows directly with the number of readings; doubling readings doubles the work.
Time Complexity: O(n)
This means the time to publish data grows linearly with the number of sensor readings.
[X] Wrong: "Sending all data at once will take the same time as sending one reading."
[OK] Correct: Each reading requires a separate send operation, so more readings mean more time.
Understanding how sending data scales helps you design efficient programs for real devices like Raspberry Pi sensors.
"What if we batch multiple sensor readings into one send? How would the time complexity change?"