0
0
Raspberry Piprogramming~5 mins

Serving sensor data as JSON API in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Serving sensor data as JSON API
O(n)
Understanding Time Complexity

When serving sensor data as a JSON API on a Raspberry Pi, it is important to understand how the time to respond grows as more data or requests come in.

We want to know how the program's work changes when the amount of sensor data or number of requests increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

from flask import Flask, jsonify
import random

app = Flask(__name__)

@app.route('/sensor')
def sensor_data():
    data = {"temperature": random.uniform(20, 30), "humidity": random.uniform(30, 50)}
    return jsonify(data)

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

This code creates a simple web server that returns current sensor data as JSON when a user visits the /sensor URL.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Generating sensor data and creating JSON response each time the /sensor URL is requested.
  • How many times: Once per request, no loops inside the handler.
How Execution Grows With Input

Each request triggers a fixed amount of work: reading sensor values and packaging them into JSON.

Input Size (n)Approx. Operations
10 requestsAbout 10 times the fixed work
100 requestsAbout 100 times the fixed work
1000 requestsAbout 1000 times the fixed work

Pattern observation: The work grows directly with the number of requests, but each request takes the same small amount of time.

Final Time Complexity

Time Complexity: O(n)

This means the total work grows linearly with the number of requests, but each request is handled quickly and independently.

Common Mistake

[X] Wrong: "The server does a lot more work as more requests come in at the same time."

[OK] Correct: Each request is handled separately and quickly; the server does not do extra work just because many requests exist, it just repeats the same small work for each.

Interview Connect

Understanding how your code handles repeated requests helps you write efficient APIs and shows you can think about performance in real projects.

Self-Check

What if the sensor_data function collected data from 100 sensors instead of 2? How would the time complexity change?