Why power management matters in Embedded C - Performance Analysis
When writing embedded C code for power management, it's important to know how the program's running time changes as input or conditions change.
We want to see how the time cost grows when managing power states in a device.
Analyze the time complexity of the following code snippet.
void manage_power(int states[], int n) {
for (int i = 0; i < n; i++) {
if (states[i] == 1) {
enter_low_power_mode();
} else {
exit_low_power_mode();
}
}
}
This code checks each power state in an array and switches modes accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array of power states.
- How many times: Exactly once for each element, so n times.
The program checks each power state one by one, so if the number of states doubles, the work doubles too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks and mode switches |
| 100 | 100 checks and mode switches |
| 1000 | 1000 checks and mode switches |
Pattern observation: The work grows directly with the number of power states.
Time Complexity: O(n)
This means the time to manage power grows in a straight line with the number of states to check.
[X] Wrong: "The program only needs to check a few states, so time stays the same no matter how many states there are."
[OK] Correct: The code actually checks every state once, so more states mean more work and more time.
Understanding how time grows with input size helps you explain your code clearly and shows you think about efficiency, which is important in embedded systems.
"What if we added nested loops to check pairs of power states? How would the time complexity change?"