0
0
Embedded Cprogramming~5 mins

Printf redirect to UART in Embedded C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Printf redirect to UART
O(n)
Understanding Time Complexity

When we redirect printf to UART, we want to know how the time taken changes as we print more characters.

We ask: How does printing more data affect the time the program spends sending it?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int _write(int file, char *ptr, int len) {
    for (int i = 0; i < len; i++) {
        while (!(UART_STATUS_REG & UART_TX_READY)) {
            ; // wait until UART is ready
        }
        UART_DATA_REG = ptr[i];
    }
    return len;
}
    

This code sends each character one by one over UART, waiting for the hardware to be ready before sending the next.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop over each character in the string to send.
  • How many times: The loop runs once for every character in the input length.
How Execution Grows With Input

As the number of characters to print grows, the time spent sending grows in the same way.

Input Size (n)Approx. Operations
10About 10 waits and sends
100About 100 waits and sends
1000About 1000 waits and sends

Pattern observation: The time grows directly with the number of characters; doubling characters doubles the time.

Final Time Complexity

Time Complexity: O(n)

This means the time to send data grows linearly with the number of characters printed.

Common Mistake

[X] Wrong: "Sending more characters takes the same time as sending one."

[OK] Correct: Each character must be sent separately, and the code waits for UART readiness each time, so more characters mean more waiting and sending steps.

Interview Connect

Understanding how hardware communication time grows with data size helps you write efficient embedded code and explain your reasoning clearly in interviews.

Self-Check

What if we changed the code to send characters in larger blocks without waiting for each one? How would the time complexity change?