Bird
0
0
Arduinoprogramming~5 mins

Wire library for I2C in Arduino - Time & Space Complexity

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

When using the Wire library for I2C communication, it's important to understand how the time to send or receive data changes as the amount of data grows.

We want to know how the time cost grows when we send more bytes over I2C.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <Wire.h>

void sendData(byte address, byte* data, int length) {
  Wire.beginTransmission(address);
  for (int i = 0; i < length; i++) {
    Wire.write(data[i]);
  }
  Wire.endTransmission();
}
    

This code sends a list of bytes to a device over I2C using the Wire library.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that calls Wire.write() for each byte.
  • How many times: Exactly length times, once per byte to send.
How Execution Grows With Input

As the number of bytes to send increases, the number of write operations grows the same way.

Input Size (n)Approx. Operations
1010 writes
100100 writes
10001000 writes

Pattern observation: The time grows directly in proportion to the number of bytes sent.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Sending more bytes takes the same time as sending just one byte."

[OK] Correct: Each byte requires a separate write operation, so more bytes mean more time spent sending.

Interview Connect

Understanding how communication time grows with data size helps you write efficient code and explain your reasoning clearly in technical discussions.

Self-Check

"What if we buffered all bytes first and sent them in one call? How would the time complexity change?"