Solution: Cost of the Simulation

What does the task-index solution from the previous section cost?

Every queue operation is , and each turn of the loop does a fixed number of them, so the cost is proportional to the number of turns the loop takes.

Let’s count the turns in the trace first. With burstTimes = [9, 2, 7] and quantum = 4, the task with burst time 9 runs for 4, then 4, then 1. That is 3 turns. The task with burst time 2 finishes in 1 turn. The task with burst time 7 runs for 4, then 3. That is 2 turns. The loop runs times in total.

Each turn of a task uses up a full quantum, except possibly the task’s last turn, which uses up whatever is left. So the number of turns a task takes is its burst time divided by the quantum, rounded up. For the first task that is , rounded up to 3. That matches the trace.

Now let’s do the same count in general. Let be the quantum and the number of tasks. A task with burst time takes turns, where means “round up to the nearest whole number”. Rounding up adds less than 1, so

Add this up over all the tasks. Write for the burst times and for their total. The number of turns is

The first line replaces each rounded-up term with the bound we just found. The second line collects the terms, which share the denominator , and collects the extra ones. The third line substitutes for the sum of the burst times.

Let’s check this against the trace. There and , so . The loop actually ran 6 times, which is under the bound, as it should be.

The setup loop that fills the queue runs times on its own. Adding that in gives at most turns across both loops. The constant 2 does not matter in big-O, so the simulation as a whole runs in time.

Can you drop the term and write instead? I think we should keep both terms because each one measures something different about the running time. The input has three parts: the number of tasks , their total burst time , and the quantum .

The while loop runs once per turn. Here are two inputs that both make it run 1000 times, for two different reasons.

  • One task with burst time 1000, and a quantum of 1. There is one task, so . But that task runs for 1 unit per turn, so it needs 1000 turns. The loop runs 1000 times. Here is what explains the count, and tells you nothing about it.
  • 1000 tasks with burst time 1 each, and a quantum of 1000. Every task finishes on its first turn, so each task takes exactly one turn. That is 1000 turns, one per task. The loop runs 1000 times. Here is what explains the count, and tells you nothing about it.

The loop runs 1000 times in both cases, but the count comes from a different term in each case. If we dropped and wrote , the first input would break the bound. If we dropped and wrote , the second input would break it. So we keep both.

I would still call the running time linear, but linear in rather than just . The method runs in time proportional to the length of the schedule it simulates.