0
0
Arduinoprogramming~5 mins

Reading data from SD card in Arduino - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reading data from SD card
O(n)
Understanding Time Complexity

When reading data from an SD card, it is important to understand how the time taken grows as the amount of data increases.

We want to know how the program's running time changes when reading more data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <SD.h>
File dataFile;

void setup() {
  SD.begin(10);
  dataFile = SD.open("data.txt");
}

void loop() {
  while (dataFile.available()) {
    char c = dataFile.read();
  }
  dataFile.close();
  while(true) {}
}
    

This code opens a file on the SD card and reads it character by character until the end.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Reading each character from the file inside the while loop.
  • How many times: Once for every character in the file until no more data is available.
How Execution Grows With Input

As the file size grows, the number of read operations grows directly with it.

Input Size (n)Approx. Operations
10 charactersAbout 10 reads
100 charactersAbout 100 reads
1000 charactersAbout 1000 reads

Pattern observation: The time grows in a straight line as the file size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to read the file grows directly with the number of characters in the file.

Common Mistake

[X] Wrong: "Reading from the SD card takes the same time no matter how big the file is."

[OK] Correct: Each character must be read one by one, so more data means more time spent reading.

Interview Connect

Understanding how reading data scales helps you write efficient code for devices with limited speed and memory.

Self-Check

"What if we read the file in larger chunks instead of one character at a time? How would the time complexity change?"