Bird
0
0
Raspberry Piprogramming~5 mins

smbus2 library for I2C in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: smbus2 library for I2C
O(n)
Understanding Time Complexity

When using the smbus2 library on a Raspberry Pi, it is important to understand how the time taken to communicate with I2C devices grows as you send more data or commands.

We want to know how the number of operations changes when reading or writing multiple bytes over I2C.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

from smbus2 import SMBus

bus = SMBus(1)
address = 0x40

# Write a list of bytes to the device
bus.write_i2c_block_data(address, 0x00, [10, 20, 30, 40, 50])

bus.close()

This code writes a block of 5 bytes to an I2C device at a given address using smbus2.

Identify Repeating Operations
  • Primary operation: Sending each byte over the I2C bus one by one.
  • How many times: Once for each byte in the list (5 times in this example).
How Execution Grows With Input

As you increase the number of bytes to send, the total time grows roughly in direct proportion.

Input Size (n)Approx. Operations
1010 byte sends
100100 byte sends
10001000 byte sends

Pattern observation: Doubling the number of bytes roughly doubles the time taken.

Final Time Complexity

Time Complexity: O(n)

This means the time to write data grows linearly with the number of bytes you send.

Common Mistake

[X] Wrong: "Sending multiple bytes at once is always as fast as sending one byte."

[OK] Correct: Each byte still requires a separate operation on the bus, so more bytes mean more time.

Interview Connect

Understanding how communication time grows with data size helps you write efficient code for hardware projects and shows you can think about performance in real devices.

Self-Check

"What if we changed from write_i2c_block_data to multiple single-byte writes? How would the time complexity change?"