Writing data to SD card in Arduino - Time & Space Complexity
When writing data to an SD card using Arduino, it's important to understand how the time taken grows as you write more data.
We want to know how the program's running time changes when the amount of data increases.
Analyze the time complexity of the following code snippet.
#include <SD.h>
File dataFile;
void setup() {
SD.begin(10);
dataFile = SD.open("data.txt", FILE_WRITE);
for (int i = 0; i < 100; i++) {
dataFile.println(i);
}
dataFile.close();
}
void loop() {}
This code opens a file on the SD card and writes 100 lines of data, then closes the file.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Writing a line to the SD card inside the for loop.
- How many times: The loop runs 100 times, writing 100 lines.
As the number of lines to write increases, the total time grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes to SD card |
| 100 | 100 writes to SD card |
| 1000 | 1000 writes to SD card |
Pattern observation: Doubling the number of lines roughly doubles the time taken.
Time Complexity: O(n)
This means the time to write data grows linearly with the number of lines you write.
[X] Wrong: "Writing to the SD card happens instantly, so time does not increase with more data."
[OK] Correct: Each write takes time because the SD card needs to physically save data, so more lines mean more time.
Understanding how writing data scales helps you design efficient programs that handle storage well, a useful skill in many real projects.
"What if we buffered multiple lines in memory and wrote them all at once? How would the time complexity change?"