Error handling in embedded projects in Arduino - Time & Space Complexity
When we add error handling in embedded projects, it can affect how long the program takes to run.
We want to know how the time to handle errors grows as the program checks more conditions or inputs.
Analyze the time complexity of the following code snippet.
void checkSensors(int sensorValues[], int size) {
for (int i = 0; i < size; i++) {
if (sensorValues[i] < 0) {
Serial.println("Error: Negative sensor value");
}
}
}
This code checks each sensor value and prints an error message if the value is negative.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop through the sensorValues array to check each value.
- How many times: The loop runs once for each sensor value, so 'size' times.
As the number of sensor values increases, the program checks more values one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of sensor values.
Time Complexity: O(n)
This means the time to handle errors grows in a straight line with the number of sensor values.
[X] Wrong: "Error handling will only take constant time no matter how many sensors there are."
[OK] Correct: Because the code checks each sensor one by one, more sensors mean more checks and more time.
Understanding how error checks affect program speed helps you write reliable embedded code that runs efficiently.
"What if we added nested loops to check pairs of sensor values? How would the time complexity change?"