Email alerts on sensor thresholds in Raspberry Pi - Time & Space Complexity
When sending email alerts based on sensor readings, it's important to know how the program's running time changes as the number of sensor checks grows.
We want to understand how the time to check sensors and send alerts grows when we have more readings.
Analyze the time complexity of the following code snippet.
for reading in sensor_readings:
if reading > threshold:
send_email_alert(reading)
This code checks each sensor reading and sends an email alert if the reading is above a set threshold.
- Primary operation: Looping through each sensor reading once.
- How many times: Once for every reading in the list.
As the number of sensor readings increases, the program checks each one once, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks, some alerts |
| 100 | 100 checks, more alerts |
| 1000 | 1000 checks, many alerts |
Pattern observation: The number of operations grows directly with the number of readings.
Time Complexity: O(n)
This means the time to check and send alerts grows in a straight line as the number of sensor readings increases.
[X] Wrong: "Sending an email alert takes no extra time, so it doesn't affect the program speed."
[OK] Correct: Sending emails can take time, especially if many alerts are sent, so it adds to the total running time.
Understanding how your program scales with more sensor data shows you can write efficient code that works well in real situations.
"What if we batch sensor readings and send one email for all alerts instead of one per reading? How would the time complexity change?"