SPI data transfer sequence in Embedded C - Time & Space Complexity
We want to understand how the time taken by SPI data transfer changes as we send more data.
How does the number of bytes affect the total time spent transferring data?
Analyze the time complexity of the following code snippet.
void spi_transfer(uint8_t *data, uint16_t length) {
for (uint16_t i = 0; i < length; i++) {
SPI_SendByte(data[i]);
while (!SPI_TransferComplete());
}
}
This code sends each byte of data one by one over SPI and waits for the transfer to finish before sending the next.
- Primary operation: Sending one byte over SPI and waiting for completion.
- How many times: This happens once for each byte in the data array, so
lengthtimes.
Each additional byte adds one more send-and-wait cycle, so the total time grows directly with the number of bytes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 send-and-wait cycles |
| 100 | 100 send-and-wait cycles |
| 1000 | 1000 send-and-wait cycles |
Pattern observation: The time increases steadily and directly as the number of bytes increases.
Time Complexity: O(n)
This means the time to transfer data grows in a straight line with the number of bytes sent.
[X] Wrong: "The transfer time stays the same no matter how many bytes we send."
[OK] Correct: Each byte requires its own send and wait, so more bytes mean more time.
Understanding how data transfer time scales helps you design efficient communication in embedded systems and shows you can analyze real hardware-related code.
"What if we used DMA (Direct Memory Access) to send data instead of sending byte-by-byte? How would the time complexity change?"