Out of curiosity I want to know how many times my program was context switched by the OS. Like all the registers were saved and the control was passed to another process or thread, and then after some time everything was restored and we continue as it never happened.
Does the system maintain such a number somewhere or is there a sort of hack or whatever?
I am on Linux in particular but I am interested about other systems as well.
Well, let's examine the case. Linux type O/S keeps these details systematically and one may use a comfort of python, for both inspecting the state and also for easy design of a monitoring system, that can report any excessive circumstances ( the former quite matching a just out of curiosity cases, the latter quite handy for any re-work / re-use for systematic work ) :
A "Monitor" example for both { voluntary | involuntary }-Ctx Switching :
The python here serves for both the educational role and for the ease and comfort of further extending the scope of functionalities:
Having assigned
signal.signal( signal.SIGALRM, SIG_ALRM_handler_A )
and the timing, the system gets ready to report both voluntary and involuntary ( enforced ) Context-Switches,for which a "FAT"-blocking piece of computing was used, that resorts, due to historical reasons to non-GIL Numpy/C/FORTRAN code and thus gets disturbed by just involuntary-CtxSwitched cases, as was shown below
(
len(str([np.math.factorial(2**f) for f in range(20)][-1]))
)but
by using a principally any other
PID
-number,this trivial monitoring mechanics can serve for whatever other purposes:
Also the Thread-level CtxSwitch details
While this was not elaborated to a similar depth, the same as above applies to: