Agent directive in Jenkins - Time & Space Complexity
We want to understand how the time it takes to run a Jenkins pipeline changes when we use the agent directive.
Specifically, how does the agent setup affect the overall execution time as the pipeline grows?
Analyze the time complexity of this Jenkins pipeline snippet using the agent directive at the top level.
pipeline {
agent any
stages {
stage('Build') {
steps {
echo 'Building...'
}
}
stage('Test') {
steps {
echo 'Testing...'
}
}
}
}
This pipeline provisions the agent once at the top level, and all stages run sequentially on that same agent.
Look for repeated actions that affect execution time.
- Fixed operation: Agent provisioning and workspace setup (O(1)).
- Primary repeating operation: Executing each stage's steps on the agent.
- How many times: Once per stage (n times).
As the number of stages (n) increases, the agent is still provisioned once, but stage executions accumulate linearly.
| Input Size (n = stages) | Approx. Operations (stage executions) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: Total execution time grows linearly with the number of stages (O(n)), dominated by stage steps. Agent setup is O(1).
Time Complexity: O(n)
This means the total time grows linearly as you add more stages, with agent setup not contributing to the growth.
[X] Wrong: "The agent is provisioned separately for each stage, causing O(n) setup overhead."
[OK] Correct: Top-level agent is provisioned once (O(1)); stages share it and run sequentially.
Understanding how Jenkins agents affect pipeline time helps you design efficient pipelines (e.g., top-level agent for many stages) and shows you know how resources impact execution.
What if we moved the agent directive inside each stage instead of at the top? How would the time complexity change? (Hint: Multiple provisions could add significant constant factors if setup is expensive.)