0
0
Raspberry Piprogramming~5 mins

REST API for IoT device in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: REST API for IoT device
O(n)
Understanding Time Complexity

When working with a REST API on an IoT device, it is important to understand how the time to handle requests changes as more data or requests come in.

We want to know how the program's work grows when the number of API calls or data size increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


from flask import Flask, request, jsonify
app = Flask(__name__)

sensor_data = []

@app.route('/data', methods=['POST'])
def add_data():
    data = request.json
    sensor_data.append(data)
    return jsonify({'status': 'success'})

@app.route('/data', methods=['GET'])
def get_data():
    return jsonify(sensor_data)

if __name__ == '__main__':
    app.run(host='0.0.0.0')
    

This code creates a simple REST API on the IoT device that stores sensor data sent by POST requests and returns all stored data on GET requests.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Returning all stored sensor data in the GET request involves traversing the entire sensor_data list.
  • How many times: The traversal happens once per GET request, and the time depends on how many data items are stored.
How Execution Grows With Input

As the number of stored sensor data items grows, the time to return all data grows too.

Input Size (n)Approx. Operations
1010 data items returned
100100 data items returned
10001000 data items returned

Pattern observation: The time to handle a GET request grows roughly in direct proportion to the number of stored data items.

Final Time Complexity

Time Complexity: O(n)

This means the time to respond grows linearly with the number of stored sensor data items.

Common Mistake

[X] Wrong: "The GET request time stays the same no matter how much data is stored."

[OK] Correct: Because the API sends all stored data each time, more data means more work and longer response time.

Interview Connect

Understanding how your IoT device handles growing data helps you design efficient APIs and shows you can think about performance in real projects.

Self-Check

"What if the GET request returned only the latest 10 data items instead of all? How would the time complexity change?"