0
0
Embedded Cprogramming~5 mins

Writing data to I2C device in Embedded C - Time & Space Complexity

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

When writing data to an I2C device, it's important to understand how the time taken grows as the amount of data increases.

We want to know how the number of bytes affects the total time spent sending data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


void i2c_write_data(uint8_t device_addr, uint8_t* data, uint16_t length) {
    i2c_start();
    i2c_send_byte(device_addr << 1); // Send device address with write bit
    for (uint16_t i = 0; i < length; i++) {
        i2c_send_byte(data[i]);
    }
    i2c_stop();
}
    

This code sends a start signal, writes the device address, then sends each byte of data one by one, and finally sends a stop signal.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Sending each byte of data inside the for-loop.
  • How many times: The loop runs once for every byte in the data array, so length times.
How Execution Grows With Input

As the number of bytes to send grows, the total time grows in a straight line with it.

Input Size (n)Approx. Operations
10About 10 send operations
100About 100 send operations
1000About 1000 send operations

Pattern observation: Doubling the data doubles the number of send operations.

Final Time Complexity

Time Complexity: O(n)

This means the time to write data grows directly in proportion to the number of bytes you send.

Common Mistake

[X] Wrong: "Sending data to an I2C device takes the same time no matter how many bytes are sent."

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

Interview Connect

Understanding how data size affects communication time helps you design efficient embedded systems and answer questions about performance in real projects.

Self-Check

"What if we buffered multiple bytes before sending them all at once? How would the time complexity change?"