CSV format data logging in Arduino - Time & Space Complexity
When logging data in CSV format on an Arduino, it's important to understand how the time to write data grows as more entries are added.
We want to know how the time needed changes when saving more lines of data.
Analyze the time complexity of the following code snippet.
void logData(float sensorValue, int entryCount) {
for (int i = 0; i < entryCount; i++) {
Serial.print(i);
Serial.print(",");
Serial.print(sensorValue);
Serial.println();
}
}
This code writes multiple lines of CSV data to the serial port, each line with an index and a sensor value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that writes each CSV line.
- How many times: It runs once for each entry, so entryCount times.
Each additional entry adds one more line to write, so the work grows steadily with the number of entries.
| Input Size (entryCount) | Approx. Operations (lines written) |
|---|---|
| 10 | 10 lines |
| 100 | 100 lines |
| 1000 | 1000 lines |
Pattern observation: The time grows directly in proportion to the number of entries.
Time Complexity: O(n)
This means the time to log data grows linearly as you add more entries.
[X] Wrong: "Writing multiple CSV lines takes the same time no matter how many lines there are."
[OK] Correct: Each line requires separate writing steps, so more lines mean more time.
Understanding how data logging time grows helps you design efficient systems that handle increasing data smoothly.
"What if we buffered multiple lines before writing them all at once? How would the time complexity change?"