Reading sensor data over I2C in Raspberry Pi - Time & Space Complexity
When reading sensor data over I2C on a Raspberry Pi, it's important to know how the time taken grows as we read more data.
We want to understand how the number of sensor reads affects the total time the program takes.
Analyze the time complexity of the following code snippet.
import smbus
bus = smbus.SMBus(1)
address = 0x48
for i in range(n):
data = bus.read_byte_data(address, 0x00)
print(f"Reading {i}: {data}")
This code reads one byte of data from a sensor at a fixed address repeatedly n times.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading one byte from the sensor using I2C bus.
- How many times: This read operation happens inside a loop that runs n times.
Each additional read adds a fixed amount of time because the sensor is read once per loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sensor reads |
| 100 | 100 sensor reads |
| 1000 | 1000 sensor reads |
Pattern observation: The total time grows directly in proportion to the number of reads.
Time Complexity: O(n)
This means if you double the number of reads, the total time roughly doubles too.
[X] Wrong: "Reading sensor data multiple times is almost instant and does not add up."
[OK] Correct: Each sensor read takes time because it communicates over I2C. Doing many reads adds up linearly.
Understanding how repeated hardware communication affects time helps you write efficient code and explain performance clearly.
What if we read multiple bytes in one I2C call instead of one byte per call? How would the time complexity change?
