0
0
Embedded Cprogramming~5 mins

GPIO port-wide operations in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: GPIO port-wide operations
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of pins increases, the loop runs more times, so the total work grows proportionally.

Input Size (pin_count)Approx. Operations
1010 operations
100100 operations
10001000 operations

Pattern observation: Doubling the number of pins roughly doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time to set all pins grows linearly with the number of pins.

Common Mistake

[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.

Interview Connect

Understanding how loops over hardware registers affect performance shows you can think about real embedded system costs, a valuable skill for many programming tasks.

Self-Check

"What if we replaced the loop with a single write that sets all pins at once? How would the time complexity change?"