Writing data to I2C device in Embedded C - Time & Space 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.
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 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
lengthtimes.
As the number of bytes to send grows, the total time grows in a straight line with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 send operations |
| 100 | About 100 send operations |
| 1000 | About 1000 send operations |
Pattern observation: Doubling the data doubles the number of send operations.
Time Complexity: O(n)
This means the time to write data grows directly in proportion to the number of bytes you send.
[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.
Understanding how data size affects communication time helps you design efficient embedded systems and answer questions about performance in real projects.
"What if we buffered multiple bytes before sending them all at once? How would the time complexity change?"