GPIO port-wide operations in Embedded C - Time & Space Complexity
When working with GPIO ports, we often perform operations on all pins at once. Understanding how the time to do this changes with the number of pins helps us write efficient code.
We want to know how the time needed grows as the port size changes.
Analyze the time complexity of the following code snippet.
// Set all pins of a GPIO port to high
void set_all_pins_high(volatile uint32_t *port, int pin_count) {
for (int i = 0; i < pin_count; i++) {
*port |= (1U << i); // Set pin i high
}
}
This code sets each pin of a GPIO port to high one by one using a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that sets each pin high.
- How many times: The loop runs once for each pin, so pin_count times.
As the number of pins increases, the loop runs more times, so the total work grows proportionally.
| Input Size (pin_count) | Approx. Operations |
|---|---|
| 10 | 10 operations |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: Doubling the number of pins roughly doubles the work done.
Time Complexity: O(n)
This means the time to set all pins grows linearly with the number of pins.
[X] Wrong: "Setting all pins at once is always constant time because it's one operation on the port register."
[OK] Correct: In this code, each pin is set individually in a loop, so the time depends on how many pins there are, not just one operation.
Understanding how loops over hardware registers affect performance shows you can think about real embedded system costs, a valuable skill for many programming tasks.
"What if we replaced the loop with a single write that sets all pins at once? How would the time complexity change?"