Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context Switch Time in Linux Kernel

In Linux Kernel when processor context switches from one thread to another , the state of the registers are saved into PCB and some more bookkeeping is done to ensure that the exact state can be loaded again.

This whole saving and loading of the registers from kernel memory might take some CPU cycles. So does this times comes under User CPU / System CPU or somewhere else

like image 316
mridul_verma Avatar asked Oct 28 '22 03:10

mridul_verma


1 Answers

Think of it like this:

  • a task is running in user-space, but something happens (syscall, exception, IRQ, ...) causing the task to switch to kernel-space

  • kernel calculates a "time spent in user-space" (now - last_time) and updates a "user time" counter for the task, and sets "last time" for later (last_time = now).

  • kernel does stuff (initially depending on what caused the switch to kernel-space), and while doing stuff it might or might not decide to do one or more task switches. When each task switch occurs kernel works out how much time the previous task spent in kernel (now - last time) and adds it to the task's "system time" and sets "last time" for later (last_time = now)

  • kernel eventually decides that the currently running task should return to user-space, and immediately before that happens it does a final update of the task's system time (now - last time again) and sets "last time" again for later (last_time = now) so that kernel can figure out "time spent in user-space" later.

  • after the task switches back to user-space, go back to the first step above and do it all again.

like image 199
Brendan Avatar answered Dec 19 '22 03:12

Brendan