Compare FCFS and shortest-job-first latency for LLM requests

Why it matters Length-aware scheduling of LLM requests can cut mean latency a lot because output lengths vary by orders of magnitude.

If a server can predict how long each request will run (for example from a predicted output length), serving short jobs first lowers average latency. Simulate both policies on one worker.

Write compare_schedulers(arrivals, service). arrivals and service are lists of floats for n requests (request i arrives at arrivals[i] and needs service[i] seconds). One worker runs one request at a time, without interruption. When the worker is free, it picks among requests that have already arrived (arrival <= current time): FCFS picks the earliest arrival; SJF picks the shortest service time. Ties go to the earlier arrival, then the lower index. If nothing has arrived, the worker idles until the next arrival. Latency of a request is finish time minus arrival time. Return (fcfs_mean, sjf_mean). For n = 0 return (0.0, 0.0).

Signaturedef compare_schedulers(arrivals, service)

Example

arrivals [0, 1, 2], service [10, 5, 1] gives (12.666666666666666, 11.333333333333334).

Understand the idea

At a photocopier, if one person has 500 pages and three people have one page each, letting the one-page people go first barely delays the big job but saves the small ones a long wait. That is shortest job first. Worked example: jobs arrive at 0, 1, 2 needing 10, 5 and 1 seconds. Both policies start the 10-second job at 0 because it is alone. At t = 10, FCFS runs the 5 then the 1, finishing at 15 and 16, so latencies are 10, 14 and 14, mean 12.67. SJF runs the 1 first, finishing at 11 and then 16, so latencies are 10, 9 and 15, mean 11.33. Rule: when free, pick among arrived jobs by the policy key. LLM schedulers use predicted output length as the job size, with aging to avoid starving long requests.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplecompare_schedulers([0, 1, 2], [10, 5, 1])
  • Sample 2: idle gapcompare_schedulers([0, 20, 20], [3, 4, 2])