Subscribing to control topics in Raspberry Pi - Time & Space Complexity
When subscribing to control topics on a Raspberry Pi, it is important to understand how the time to process messages grows as more topics or messages are involved.
We want to know how the program's work changes when the number of subscribed topics or incoming messages increases.
Analyze the time complexity of the following code snippet.
import paho.mqtt.client as mqtt
def on_message(client, userdata, message):
print(f"Received message: {message.payload.decode()}")
client = mqtt.Client()
topics = ["control/led", "control/motor", "control/sensor"]
for topic in topics:
client.subscribe(topic)
client.on_message = on_message
client.loop_start()
This code subscribes to a list of control topics and prints messages received on them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over the list of topics to subscribe.
- How many times: Once for each topic in the list.
As the number of topics increases, the number of subscribe calls grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 subscribe calls |
| 10 | 10 subscribe calls |
| 100 | 100 subscribe calls |
Pattern observation: The work grows in a straight line with the number of topics.
Time Complexity: O(n)
This means the time to subscribe grows directly with the number of topics you want to listen to.
[X] Wrong: "Subscribing to multiple topics happens all at once and takes the same time no matter how many topics there are."
[OK] Correct: Each topic requires a separate subscribe call, so more topics mean more work and more time.
Understanding how subscribing scales helps you design efficient IoT applications on Raspberry Pi, showing you can think about performance as your projects grow.
"What if we batch subscribe to all topics in one call? How would the time complexity change?"