Why data logging matters for IoT in Raspberry Pi - Performance Analysis
When working with IoT devices like Raspberry Pi, data logging collects sensor readings over time. We want to understand how the time to save data grows as more readings are collected.
How does the time needed to log data change as the amount of data grows?
Analyze the time complexity of the following data logging code snippet.
import time
def log_data(sensor_readings):
with open('data_log.txt', 'a') as file:
for reading in sensor_readings:
file.write(f"{reading}\n")
time.sleep(0.01) # simulate delay
# sensor_readings is a list of values
This code appends each sensor reading to a file one by one, simulating a small delay for each write.
Look at what repeats as input grows.
- Primary operation: Loop over each sensor reading to write it to the file.
- How many times: Once for each reading in the input list.
As the number of readings increases, the time to log grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 writes and delays |
| 100 | 100 writes and delays |
| 1000 | 1000 writes and delays |
Pattern observation: Doubling the readings roughly doubles the time taken.
Time Complexity: O(n)
This means the time to log data grows directly with the number of readings.
[X] Wrong: "Writing to a file once means logging many readings is always fast."
[OK] Correct: Each reading is written separately, so more readings mean more writes and more time.
Understanding how data logging time grows helps you design efficient IoT systems and shows you can think about real-world resource use.
"What if we buffered all readings and wrote them to the file in one go? How would the time complexity change?"