The "Stop-and-Go" Penalty
Swapping processes in and out of the CPU thousands of times per second is not free. Each swap is called a context switch, and it carries real overhead.
Imagine a surgeon (the CPU) performing an operation (Process A). The hospital administrator (the scheduler) suddenly says: "Stop — you need to go to operating room 2 immediately (Process B)." The surgeon cannot just teleport. They must:
- Pause the current procedure safely.
- Document exactly where they left off (suture count, instrument positions).
- Walk to the other room.
- Read the other patient's chart and resume from where that procedure was paused.
In computing, a context switch requires the kernel to:
- Save the running process's CPU register state (program counter, stack pointer, general-purpose registers) into its Process Control Block (PCB) in memory.
- Save the memory management state (page table pointer, TLB entries).
- Load the saved register state of the incoming process.
- Flush the CPU's Translation Lookaside Buffer (TLB) if the two processes have different address spaces (on most architectures).
The TLB flush is particularly expensive. The TLB is a hardware cache that speeds up virtual-to-physical memory address translation. After a context switch to a different process, the TLB contains stale entries for the old process, and the new process must rebuild it from scratch — causing a burst of slow memory lookups until the TLB warms up again.
A single context switch takes roughly 1–10 microseconds depending on hardware. At 1,000 switches per second, that is 1–10ms of pure overhead per second per core — CPU time spent switching rather than doing useful work. This is why the scheduler tries to balance fairness with minimizing unnecessary switches, and why long-running CPU-bound tasks benefit from larger time slices.
A common SRE interview question is: "Your application's CPU usage is high but throughput is low. What would you look for?" One answer is excessive context switching. You can diagnose this with vmstat 1 (look at the cs column) or pidstat -w 1. If context switches per second are in the millions, the system may be thrashing — too many threads competing for too few cores. The fix is often reducing thread count or using async I/O to reduce the number of runnable threads.