mosquitto_pub and mosquitto_sub commands in IOT Protocols - Time & Space Complexity
We want to understand how the time to send and receive messages using mosquitto_pub and mosquitto_sub changes as the number of messages grows.
How does the command execution time grow when more messages are published or subscribed?
Analyze the time complexity of the following commands.
# Publish 100 messages to topic 'sensor/data'
for i in $(seq 1 100); do
mosquitto_pub -t sensor/data -m "Message $i"
done
# Subscribe to topic 'sensor/data' and print messages
mosquitto_sub -t sensor/data
This code publishes 100 messages one by one and subscribes to receive messages from the same topic.
Look at what repeats in these commands.
- Primary operation: Publishing messages in a loop.
- How many times: The publish command runs once per message, so 100 times here.
As the number of messages increases, the total time grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 publish commands |
| 100 | 100 publish commands |
| 1000 | 1000 publish commands |
Pattern observation: Doubling the number of messages doubles the total publish operations and time.
Time Complexity: O(n)
This means the time to publish messages grows linearly with the number of messages sent.
[X] Wrong: "Publishing multiple messages at once takes the same time as publishing one message."
[OK] Correct: Each message requires a separate publish operation, so more messages mean more time.
Understanding how message publishing scales helps you design efficient IoT systems and shows you can reason about command execution time in real scenarios.
"What if we batch multiple messages into one publish command? How would the time complexity change?"