SPI with display modules in Raspberry Pi - Time & Space Complexity
When using SPI to send data to display modules, it's important to understand how the time to send data grows as the amount of data increases.
We want to know how the communication time changes when we send more pixels or commands.
Analyze the time complexity of the following SPI data sending code.
import spidev
spi = spidev.SpiDev()
spi.open(0, 0)
pixels = [0xFF, 0x00, 0xAA, 0x55] * 100 # Example pixel data
for pixel in pixels:
spi.xfer([pixel]) # Send one byte per pixel
spi.close()
This code sends a list of pixel bytes one by one over SPI to a display module.
- Primary operation: Sending one byte over SPI inside a loop.
- How many times: Once for each pixel in the list.
Each pixel byte requires one SPI transfer, so the total time grows as we add more pixels.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 SPI transfers |
| 100 | 100 SPI transfers |
| 1000 | 1000 SPI transfers |
Pattern observation: The time grows directly in proportion to the number of pixels sent.
Time Complexity: O(n)
This means the time to send data grows linearly with the number of pixels.
[X] Wrong: "Sending more pixels doesn't affect the total time much because SPI is fast."
[OK] Correct: Even though SPI is fast, each pixel still requires a separate transfer, so more pixels mean more time overall.
Understanding how data transfer time grows with data size helps you design efficient communication with hardware, a useful skill in many projects and interviews.
"What if we send multiple pixels in one SPI transfer instead of one byte at a time? How would the time complexity change?"
