0
0
Goprogramming~5 mins

Concurrent execution model in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Concurrent execution model
O(1)
Understanding Time Complexity

When programs run tasks at the same time, it changes how long things take. We want to see how running tasks together affects the total work done.

How does doing many tasks at once change the time needed as we add more tasks?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

package main

import (
	"fmt"
	"sync"
	"time"
)

func worker(id int, wg *sync.WaitGroup) {
	defer wg.Done()
	time.Sleep(1 * time.Second) // simulate work
	fmt.Println("Worker", id, "done")
}

func main() {
	var wg sync.WaitGroup
	for i := 1; i <= 5; i++ {
		wg.Add(1)
		go worker(i, &wg)
	}
	wg.Wait()
}

This code runs 5 workers at the same time, each doing a 1-second task concurrently.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Starting 5 concurrent worker tasks.
  • How many times: 5 times, once per worker.
How Execution Grows With Input

Each worker runs independently, so total time depends on the longest single task, not the sum.

Input Size (n)Approx. Operations (seconds)
51 (all run together)
101 (still all run together)
1001 (assuming enough resources to run all)

Pattern observation: Total time stays about the same as tasks increase, if they run truly in parallel.

Final Time Complexity

Time Complexity: O(1)

This means the total time does not grow with more tasks because they run at the same time.

Common Mistake

[X] Wrong: "Adding more concurrent tasks always makes the program slower because it does more work."

[OK] Correct: When tasks run at the same time, total time depends on the longest task, not the number of tasks.

Interview Connect

Understanding how concurrency affects time helps you explain real programs that do many things at once. It shows you can think about how work spreads out over time.

Self-Check

"What if each worker took different amounts of time? How would that affect the total time complexity?"