Bird
0
0
Raspberry Piprogramming~5 mins

Reading sensor data over I2C in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reading sensor data over I2C
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each additional read adds a fixed amount of time because the sensor is read once per loop.

Input Size (n)Approx. Operations
1010 sensor reads
100100 sensor reads
10001000 sensor reads

Pattern observation: The total time grows directly in proportion to the number of reads.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of reads, the total time roughly doubles too.

Common Mistake

[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.

Interview Connect

Understanding how repeated hardware communication affects time helps you write efficient code and explain performance clearly.

Self-Check

What if we read multiple bytes in one I2C call instead of one byte per call? How would the time complexity change?