Embedded Coder for MCU deployment in Simulink - Time & Space Complexity
When generating code for microcontrollers using Embedded Coder, it's important to understand how the time to run the generated code grows as input size or model complexity increases.
We want to know how the execution time changes when the model or input data gets bigger.
Analyze the time complexity of the following Simulink model code snippet generated for MCU deployment.
// Initialize variables
int sum = 0;
for (int i = 0; i < N; i++) {
sum += inputArray[i];
}
output = sum / N;
This code calculates the average of an array of size N by summing all elements and dividing by N.
Look for loops or repeated steps that take most time.
- Primary operation: The for-loop that adds each element of the input array.
- How many times: Exactly N times, once for each element.
As the input size N grows, the number of additions grows the same way.
| Input Size (N) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the size of the input array.
Time Complexity: O(N)
This means the time to run the code grows in a straight line as the input size increases.
[X] Wrong: "The code runs in constant time because it just sums numbers."
[OK] Correct: The code must look at every number once, so the time grows with how many numbers there are.
Understanding how code runs on microcontrollers helps you write efficient embedded software and explain your reasoning clearly in real projects or interviews.
"What if the code used two nested loops over the input array? How would the time complexity change?"