Stack size allocation in FreeRTOS - Time & Space Complexity
When we allocate stack size in FreeRTOS tasks, we want to know how the time to allocate grows as the stack size changes.
We ask: How does increasing the stack size affect the time the system spends setting it up?
Analyze the time complexity of the following code snippet.
// Create a task with a given stack size
xTaskCreate(
TaskFunction, // Task function
"TaskName", // Name
stackSize, // Stack size in words
NULL, // Parameters
tskIDLE_PRIORITY, // Priority
NULL // Task handle
);
This code creates a FreeRTOS task and allocates memory for its stack based on stackSize.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Allocating and initializing the stack memory of size
stackSize. - How many times: The system sets up each stack element once during allocation.
As the stack size increases, the system spends more time setting up the stack memory.
| Input Size (stackSize) | Approx. Operations |
|---|---|
| 10 | 10 operations (setting up each stack word) |
| 100 | 100 operations |
| 1000 | 1000 operations |
Pattern observation: The time grows directly with the stack size; doubling the stack size roughly doubles the setup time.
Time Complexity: O(n)
This means the time to allocate and initialize the stack grows linearly with the stack size.
[X] Wrong: "Allocating a larger stack size takes the same time as a smaller one because it's just one call."
[OK] Correct: Even though it's one function call, the system must set up each stack element, so bigger stacks take more time.
Understanding how stack size affects allocation time helps you reason about resource use in embedded systems, a key skill for real-world programming.
"What if the stack memory was allocated from a pre-allocated pool instead of dynamically? How would the time complexity change?"