pyserial library usage in Raspberry Pi - Time & Space Complexity
When using the pyserial library on a Raspberry Pi, it is important to understand how the time taken by the program changes as it reads or writes data.
We want to know how the program's running time grows when handling more data through the serial port.
Analyze the time complexity of the following code snippet.
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600)
data = []
for _ in range(100):
line = ser.readline()
data.append(line)
ser.close()
This code opens a serial connection, reads 100 lines of data, stores them in a list, and then closes the connection.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading a line from the serial port inside a loop.
- How many times: Exactly 100 times, once per loop iteration.
Each line read takes some time, so if we increase the number of lines, the total time grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads from serial port |
| 100 | 100 reads from serial port |
| 1000 | 1000 reads from serial port |
Pattern observation: Doubling the number of lines doubles the total reading time.
Time Complexity: O(n)
This means the time to read data grows directly in proportion to how many lines you read.
[X] Wrong: "Reading from the serial port is instant, so time does not depend on how many lines we read."
[OK] Correct: Each read waits for data to arrive, so more lines mean more waiting and more time spent.
Understanding how reading data scales helps you write efficient programs that handle serial communication smoothly on devices like Raspberry Pi.
"What if we changed the code to read data only when available using a non-blocking method? How would the time complexity change?"
