OLED display with I2C (SSD1306) in Raspberry Pi - Time & Space Complexity
When working with an OLED display using I2C, it's important to understand how the time to update the screen changes as the amount of data grows.
We want to know how the program's running time changes when sending more pixels or commands to the display.
Analyze the time complexity of the following code snippet.
import board
import busio
from adafruit_ssd1306 import SSD1306_I2C
# Initialize I2C and display
i2c = busio.I2C(board.SCL, board.SDA)
display = SSD1306_I2C(128, 64, i2c)
display.fill(0) # Clear display
for y in range(64):
for x in range(128):
display.pixel(x, y, 1) # Turn pixel on
display.show() # Update display
This code turns on every pixel on a 128x64 OLED display using I2C communication.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Setting each pixel on the display inside nested loops.
- How many times: 128 (width) x 64 (height) = 8192 times.
As the display size grows, the number of pixels to set grows with the total number of pixels.
| Input Size (pixels) | Approx. Operations |
|---|---|
| 10x10 = 100 | 100 pixel sets |
| 100x100 = 10,000 | 10,000 pixel sets |
| 1000x1000 = 1,000,000 | 1,000,000 pixel sets |
Pattern observation: The operations grow proportionally with the number of pixels, so doubling width and height quadruples the work.
Time Complexity: O(n)
This means the time to update the display grows directly with the number of pixels you want to change.
[X] Wrong: "Updating the display takes the same time no matter how many pixels I change."
[OK] Correct: Each pixel update requires time to update the internal buffer, so more pixels mean more time spent preparing data before sending over I2C.
Understanding how hardware communication scales with data size helps you write efficient code and explain performance in real projects.
"What if we only update a small portion of the display instead of all pixels? How would the time complexity change?"
