Pressing the infamous ctl-alt-del keys on a Windows machine will bring up the Task Manager application. One of the tabs shows the running processes and their respective CPU usage, in percent.
Recently, in a conversation, the subject of how exactly this number is obtained came up. No one knew. So I’m left to ask you good folks: how?
I’ve never seen the windows source code, but in general an operating system works on “time slices.” The kernal of the operating system gets called very regularly from the time tick interrupt, and during each tick it decides if it is going to allow the current task to continue executing or if it is going to swap in a new task (this section of the operating system is called the “scheduler” since it schedules tasks for execution). All it has to do is keep track of how many time slices get allocated to each task and divide it by the total number of time slices in the period being examined (probably about 1 second).
The task manager application simply reads this information out of the task control blocks.