25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Solutions to Chapter 18 | Threads and Locks<br />

18 2 How can you measure <strong>the</strong> time spent in a context switch?<br />

SOLUTION<br />

This is a tricky question, but let’s start with a possible solution<br />

CareerCup com<br />

pg 86<br />

A context switch is <strong>the</strong> time spent switching between two processes (e g , bringing a waiting<br />

process into execution and sending an executing process into waiting/terminated state)<br />

This happens in multitasking The operating system must bring <strong>the</strong> state information of<br />

waiting processes into memory and save <strong>the</strong> state information of <strong>the</strong> running process<br />

In order to solve this problem, we would like to record timestamps of <strong>the</strong> last and first instruction<br />

of <strong>the</strong> swapping processes The context switching time would be <strong>the</strong> difference in<br />

<strong>the</strong> timestamps between <strong>the</strong> two processes<br />

Let’s take an easy example: Assume <strong>the</strong>re are only two processes, P1 and P2<br />

P1 is executing and P2 is waiting for execution At some point, <strong>the</strong> OS must swap P1 and<br />

P2—let’s assume it happens at <strong>the</strong> Nth instruction of P1 So, <strong>the</strong> context switch time for this<br />

would be Time_Stamp(P2_1) – Time_Stamp(P2_N)<br />

Easy enough The tricky part is this: how do we know when this swapping occurs? Swapping<br />

is governed by <strong>the</strong> scheduling algorithm of <strong>the</strong> OS We can not, of course, record <strong>the</strong><br />

timestamp of every instruction in <strong>the</strong> process<br />

Ano<strong>the</strong>r issue: <strong>the</strong>re are many kernel level threads which are also doing context switches,<br />

and <strong>the</strong> user does not have any control over <strong>the</strong>m<br />

Overall, we can say that this is mostly an approximate calculation which depends on <strong>the</strong><br />

underlying OS One approximation could be to record <strong>the</strong> end instruction timestamp of a<br />

process and start timestamp of a process and waiting time in queue<br />

If <strong>the</strong> total timeof execution of all <strong>the</strong> processes was T, <strong>the</strong>n <strong>the</strong> context switch time = T –<br />

(SUM for all processes (waiting time + execution time))<br />

2 5 8

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!