GPIO register configuration in Embedded C - Time & Space Complexity
We want to understand how the time to configure GPIO registers changes as we configure more pins.
How does the work grow when we set up many pins one by one?
Analyze the time complexity of the following code snippet.
// Configure GPIO pins one by one
for (int i = 0; i < num_pins; i++) {
GPIO->MODER &= ~(0x3 << (2 * i)); // Clear mode bits
GPIO->MODER |= (0x1 << (2 * i)); // Set pin as output
}
This code sets each GPIO pin mode to output by updating register bits in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop that updates GPIO register bits for each pin.
- How many times: Exactly once per pin, so
num_pinstimes.
Each pin requires a fixed number of steps to configure, so total work grows directly with number of pins.
| Input Size (num_pins) | Approx. Operations |
|---|---|
| 10 | About 10 register updates |
| 100 | About 100 register updates |
| 1000 | About 1000 register updates |
Pattern observation: The work grows steadily and directly with the number of pins.
Time Complexity: O(n)
This means the time to configure GPIO pins grows linearly as you add more pins.
[X] Wrong: "Configuring multiple pins at once takes the same time as one pin."
[OK] Correct: Each pin requires separate register updates, so more pins mean more work.
Understanding how loops affect time helps you explain embedded code efficiency clearly and confidently.
"What if we configure all pins by writing once to the register instead of looping? How would the time complexity change?"