operating-system-context-switching.html


* created: 2025-05-17T23:01
* modified: 2025-07-08T12:52

title

Context switching

description

Saving the state of one process and loading the state of another. This is usefull for interactive applications, but not required if you have strictly linear tasks. You can measure context switches using the `vmstat` command.

related notes

Context switching

Context switching describes the process of loading storing the context of one process and loading another. This is handled by the control unit of the CPU and the operating system.

In general a context switch happens in two distinct steps which are:

  1. Save the context of the context of the currently running process into a known location inside the main memory.
  2. Load the required state of the program that is to be executed in CPU registers and cache.

What are the benefits and downsides?

Benefits:

Downsides:

When does a context switch happen?

There are multiple reasons for a context switch to occur. The simplest answer would be, that a context switch happens any time, that another process becomes “more important” than another (see scheduling). These changing priorities often coincide with:

Measuring context switches

You can measure the ongoing context switches on Linux systems using the vmstat command. This takes two inputs, the time interval and the amount of times the data should be logged. The context switches can be found under the cs section of the output.

Running vmstat 2 5 for example logs every 2 seconds for five times and produces a output that looks something like this:

procs -----------memory---------- ---swap-- -----io---- -system-- -------cpu-------
r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st gu
1  0      0 2327032 202748 2395872    0    0   250   112 8063    4  3  2 95  0  0  0
0  0      0 2330848 202764 2395876    0    0     0   258  934  837  1  1 98  0  0  0
0  0      0 2330848 202764 2395876    0    0     0     0  434  419  0  0 99  0  0  0
0  0      0 2330784 202764 2395876    0    0     0    34 3146 1640  2  1 97  0  0  0
0  0      0 2330784 202772 2395876    0    0     0    42 1389  920  1  1 98  0  0  0