Multi-device MQTT network in Raspberry Pi - Time & Space Complexity
When many Raspberry Pi devices send messages using MQTT, we want to know how the time to process messages grows as more devices join.
We ask: How does adding more devices affect the work the network does?
Analyze the time complexity of the following code snippet.
import paho.mqtt.client as mqtt
clients = []
for i in range(n):
client = mqtt.Client(f"device_{i}")
client.connect("broker.local")
client.loop_start()
clients.append(client)
for client in clients:
client.publish("sensor/data", "message")
This code connects n devices to an MQTT broker and each device sends one message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over
ndevices to connect and send messages. - How many times: Each loop runs
ntimes, once per device.
As the number of devices n grows, the total work grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (connect + publish per device) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: Doubling devices roughly doubles the work needed.
Time Complexity: O(n)
This means the time to connect and send messages grows directly with the number of devices.
[X] Wrong: "Adding more devices won't affect the time much because messages are sent independently."
[OK] Correct: Each device adds its own connection and message sending steps, so total work adds up linearly.
Understanding how work grows with devices helps you design scalable IoT systems and shows you can think about performance in real networks.
What if each device sends m messages instead of one? How would the time complexity change?