Configuring pin as input or output in Embedded C - Performance & Efficiency
When configuring a pin as input or output, the code runs a few simple steps.
We want to see how the time it takes changes if we do this for many pins.
Analyze the time complexity of the following code snippet.
void configure_pins(int pins[], int n) {
for (int i = 0; i < n; i++) {
if (pins[i] % 2 == 0) {
// Set pin as output
set_pin_output(pins[i]);
} else {
// Set pin as input
set_pin_input(pins[i]);
}
}
}
This code sets each pin in the array as input or output based on whether the pin number is even or odd.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each pin in the array.
- How many times: Exactly once for each pin, so n times.
As the number of pins increases, the time to configure them grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times setting pins |
| 100 | 100 times setting pins |
| 1000 | 1000 times setting pins |
Pattern observation: Doubling the pins doubles the work needed.
Time Complexity: O(n)
This means the time to configure pins grows directly with the number of pins.
[X] Wrong: "Configuring pins is always constant time no matter how many pins."
[OK] Correct: Each pin needs its own setup step, so more pins mean more time.
Understanding how loops affect time helps you explain how embedded code scales with hardware changes.
"What if we configure pins in pairs instead of one by one? How would the time complexity change?"