Writing commands to I2C device in Raspberry Pi - Time & Space 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.
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.
- Primary operation: Sending a command using
bus.write_byteinside a loop. - How many times: Once for each command in the list.
Each command requires one write operation, so the total time grows directly with the number of commands.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 write operations |
| 100 | 100 write operations |
| 1000 | 1000 write operations |
Pattern observation: The time increases steadily as more commands are sent, growing in a straight line.
Time Complexity: O(n)
This means the time to send commands grows directly in proportion to how many commands you send.
[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.
Understanding how communication time grows with commands helps you design efficient device interactions and shows you can reason about real hardware tasks.
"What if we batch multiple commands into one write operation? How would the time complexity change?"
