Printf redirect to UART in Embedded C - Time & Space 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?
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 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.
As the number of characters to print grows, the time spent sending grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 waits and sends |
| 100 | About 100 waits and sends |
| 1000 | About 1000 waits and sends |
Pattern observation: The time grows directly with the number of characters; doubling characters doubles the time.
Time Complexity: O(n)
This means the time to send data grows linearly with the number of characters printed.
[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.
Understanding how hardware communication time grows with data size helps you write efficient embedded code and explain your reasoning clearly in interviews.
What if we changed the code to send characters in larger blocks without waiting for each one? How would the time complexity change?