Bird
0
0
Raspberry Piprogramming~5 mins

Writing commands to I2C device in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing commands to I2C device
O(n)
Understanding Time Complexity

When writing commands to an I2C device, it is important to understand how the time taken grows as we send more commands.

We want to know how the number of commands affects the total time spent communicating.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


import smbus

bus = smbus.SMBus(1)
address = 0x40

commands = [0x01, 0x02, 0x03, 0x04]
for cmd in commands:
    bus.write_byte(address, cmd)
    

This code sends a list of commands one by one to an I2C device at a specific address.

Identify Repeating Operations
  • Primary operation: Sending a command using bus.write_byte inside a loop.
  • How many times: Once for each command in the list.
How Execution Grows With Input

Each command requires one write operation, so the total time grows directly with the number of commands.

Input Size (n)Approx. Operations
1010 write operations
100100 write operations
10001000 write operations

Pattern observation: The time increases steadily as more commands are sent, growing in a straight line.

Final Time Complexity

Time Complexity: O(n)

This means the time to send commands grows directly in proportion to how many commands you send.

Common Mistake

[X] Wrong: "Sending multiple commands at once takes the same time as sending one command."

[OK] Correct: Each command requires a separate write operation, so time adds up with each command sent.

Interview Connect

Understanding how communication time grows with commands helps you design efficient device interactions and shows you can reason about real hardware tasks.

Self-Check

"What if we batch multiple commands into one write operation? How would the time complexity change?"