How computers work

The journey of a keypress: from finger to pixel

You pressed “A” in a text editor, and the letter appeared on the screen, seemingly instantly. In reality, in those 10–50 milliseconds a microcontroller in the keyboard, the USB bus, a controller in the chipset, a processor interrupt, three layers of drivers, the OS window system, the program, the graphics card and the liquid crystals of the monitor all did their part. Let’s follow this path step by step and count what each step costs.

Open on the site →

Keyboard: the matrix and the microcontroller

There is no separate wire to each key: there are about a hundred of them, and they are connected in a matrix, for example 6 rows × 21 columns. Each key closes the intersection of its row and column. The keyboard’s microcontroller applies voltage to the columns one at a time and reads the rows: if a signal appears on row 3 while column 2 is active, the key at that intersection is pressed. A full scan of the matrix takes a fraction of a millisecond, and it repeats continuously.

A mechanical contact does not close cleanly: the metal bounces, and in the first milliseconds the contact opens and closes several times. This is called “bounce.” If every closure were counted as a press, you would get “aaa” instead of a single “a.” So the keyboard firmware filters out bounce: it waits until the state settles, typically 5 ms, or it registers the first closure but ignores further changes for a few more milliseconds.

If you hold down several keys at once, in a simple matrix the current can take a detour through three pressed keys, and the controller will “see” a fourth that nobody pressed (ghosting). Expensive keyboards put a diode on every key and recognize any number of simultaneous presses (NKRO); cheap ones simply block suspicious combinations, which is where the “three keys won’t register at once” problem in games comes from.

What the microcontroller produces is not a letter but a key code. For USB keyboards it is a code from the HID standard: the “A” key has code 0x04 regardless of the layout. Whether it becomes a Latin “a,” the Russian letter that sits on that key, or a capital “A” is decided not by the keyboard but by the OS. In the model this step takes about 1 ms.

See also: Workstation: the whole computer

USB: the computer asks, the keyboard answers

A USB keyboard cannot simply “send” a keypress: in USB, all communication is initiated by the computer. When connected, the keyboard announces that it is an HID-class device with an interrupt endpoint and a polling interval. The computer’s host controller polls it at that interval: ordinary keyboards 125–1,000 times per second (every 8 or 1 ms), gaming keyboards on high-speed USB up to 8,000 times (every 125 µs).

If nothing has changed since the last poll, the keyboard replies “no data.” If something has changed, it sends a report. The standard boot-protocol report is 8 bytes: a modifier byte (bits for left and right Ctrl, Shift, Alt and Win), a reserved byte, and the codes of up to six keys pressed at the same time. Pressing “A” is the report 00 00 04 00 00 00 00 00; releasing it is a report of zeros.

Physically, the bytes travel over the differential pair of wires D+ and D− in the USB cable at 12 Mbit/s (full-speed mode, which is far more than a keyboard needs): 8 bytes with packet headers are transmitted in a few microseconds. The main delay in this step is waiting for the next poll: on average half the interval, about 0.5 ms at 1,000 Hz and 4 ms at 125 Hz.

The old PS/2 connector worked the other way around: the keyboard itself initiated the transfer and triggered a processor interrupt directly. That is why a myth long persisted among gamers that PS/2 is “faster.” With 1,000 Hz polling the difference disappears, and the OS processing is comparable on both paths.

The host controller and DMA

Polling is handled by the USB host controller (the xHCI standard), usually in the chipset and sometimes right in the processor. It is an independent device on PCIe with its own registers. The OS driver has placed in main memory, in advance, a ring queue of “transfer descriptors” with buffer addresses: “when the keyboard sends data, put it here.”

Having received 8 bytes from the keyboard, the controller writes them into main memory by itself via DMA: over the chipset link into the processor, from there to the memory controller and into the DDR5 module. It then writes a 16-byte record, “transfer complete, 8 bytes,” into another ring queue, the event queue. The processor did not spend a single cycle on this.

To let the OS know about the new event, the controller sends an MSI-X interrupt, a special write to the address of the processor’s interrupt controller. Controllers often hold interrupts back a little (moderation) so as not to wake the processor for every single event in a stream. This whole step takes microseconds.

See also: Motherboard: how everything is connected

The interrupt: the processor sets its work aside

The interrupt controller (APIC) picks a processor core and signals it. At that moment the core could be doing anything: compiling, running a video game, or nothing at all (sleeping in a power-saving state, in which case it first has to wake up, which from deep sleep takes tens of microseconds). The core finishes its current instructions, saves the program counter and flags, switches to kernel mode and jumps via the interrupt vector table to the xHCI driver’s handler.

The interrupt handler must be very short, because while it runs the core does nothing else. It reads the event queue, notes that data have arrived from the keyboard, and defers the main work: in Linux to a deferred handler (a softirq or a thread), in Windows to a DPC, a deferred procedure call. Then the core returns to the interrupted program, which does not even notice the pause of a few microseconds.

Note that the interrupt came not “from the keyboard” and not “on the keypress,” as old-fashioned explanations often say, but from the USB controller when the poll completed. The keyboard merely answered a question. In the model the DMA and interrupt steps take tens of microseconds, next to nothing compared with the other stages.

See also: The processor core: an educational datapath and a modern core

Drivers: from report to key event

Next the report climbs up a stack of drivers. The xHCI driver passes the data to the USB core, which passes it to the HID class driver, and that driver parses the report: it compares it with the previous one and sees that code 0x04 has appeared, meaning the A key is pressed. The HID driver translates it into the OS’s internal key code: in Linux that is KEY_A with number 30 (amusingly, the same number as this key’s scan code in the old IBM PC set), in Windows a scan code and the virtual key code VK_A.

In Linux the event goes into the input subsystem and appears in the device file /dev/input/eventN as a record “time, type: key, code: 30, value: 1 (pressed).” In Windows the keyboard driver passes it to the win32k window subsystem, into the raw input thread.

Autorepeat, when a character starts repeating as you hold a key down, is also done by the OS, not by the keyboard: 0.25–0.6 s after the press it starts generating repeat events 25–30 times per second until a release report arrives.

All of this runs in kernel mode at high priority and takes tens to hundreds of microseconds. In the model the OS step is estimated at 0.2 ms.

See also: The operating system: who shares out the processor, memory and devices

The window system: who gets the keypress

There are many windows on the screen, but a keypress must go to just one: the window with input focus. That is decided by the window system. In Windows the raw input thread determines which thread owns the active window and puts a WM_KEYDOWN message into its queue. In Linux with Wayland the compositor (GNOME Shell, KWin, Sway) reads the device events, applies the layout itself and sends the event to the focused client over a socket.

This is where the key code is turned into a character for the first time. The layout table maps key 30, taking into account the modifiers and the active language: without Shift on the English layout it is “a,” with Shift it is “A,” and on the Russian layout it is the Cyrillic letter that sits on that key. In Windows the program calls TranslateMessage for this, and one more message is added to the queue: WM_CHAR with the character’s Unicode code. Combinations such as Alt+Tab are intercepted earlier and never reach the program at all.

The receiving program’s thread has been sleeping all this time, waiting for messages in a system call such as GetMessage or poll. The arrival of the event wakes it: the OS scheduler marks the thread as ready and, since it was waiting for input, puts it on a core almost immediately, usually within tens of microseconds. But if the processor is overloaded and the program has low priority, this is exactly where a noticeable delay can appear.

See also: The operating system: who shares out the processor, memory and devices · Inside the browser: from HTML bytes to pixels on the screen

The program: the character enters the document

The program receives the event in its processing loop and calls a handler. In an editor the handler inserts the character “a” into the document structure at the cursor position, moves the cursor, adds the action to the undo history, and perhaps triggers autocompletion or a spell check. In a browser the path is longer: the browser process passes the event to the tab process, where the keydown, beforeinput and input events fire for JavaScript, and then the text field changes the DOM.

Next the changed line has to be laid out again. The text is turned into font glyphs (for this the font looks up the needed character and applies kerning and ligatures), the line is measured, and if it no longer fits, line wrapping pushes everything below it down. The program marks the changed area of the window as needing to be redrawn and asks the OS for a new frame.

This step depends on the program more than any other. A simple editor written in C fits into a fraction of a millisecond. An editor built on web technologies with syntax highlighting, error checking and extensions can spend 5–30 ms. The model budgets 2 ms, typical of a well-written program.

See also: Inside the browser: from HTML bytes to pixels on the screen · Languages and runtimes: how program text becomes processor instructions · The processor core: an educational datapath and a modern core

Rendering: a frame on the graphics card

The program draws the changed area: the background, the text, the cursor. Modern programs almost always do this with the graphics card. The letter glyphs are drawn in advance into an atlas texture, and drawing a line of text is a set of rectangles, onto each of which the graphics card maps a piece of the atlas. The drawing commands are collected into a buffer and handed to the graphics driver.

Then the system compositor gets to work (DWM in Windows, WindowServer in macOS, the Wayland compositor in Linux): it takes the images of all the windows and assembles the final frame from them in the framebuffer, the video memory that holds the finished picture of the screen. The compositor works to the rhythm of vertical sync: it assembles the frame by the moment the monitor begins to output the next one.

This is the source of an important component of latency: waiting for the frame. At 60 Hz a frame lasts 16.7 ms. If the program finishes drawing right after the compositor has assembled a frame, its change will wait for the next one. On average this adds half a frame, and with double or triple buffering, one or two whole frames. At 144 Hz a frame is just 6.9 ms, and the gain is noticeable even when typing.

See also: Graphics card: how an image appears · Inside the browser: from HTML bytes to pixels on the screen

The monitor: from signal to light

The graphics card’s display engine reads the framebuffer line by line and sends the pixels down a DisplayPort or HDMI cable. DisplayPort 1.4 carries up to 32.4 Gbit/s over four pairs, DisplayPort 2.1 up to 80 Gbit/s, HDMI 2.1 up to 48 Gbit/s; a 2560 × 1440 picture at 144 Hz needs about 13 Gbit/s. A frame is not transmitted instantly but over the whole scan time, top to bottom in 7–17 ms, so a letter at the bottom of the screen will appear later than one at the top.

The monitor’s controller receives the stream, scales the picture if needed and processes it (panel overdrive, color correction), and then the panel’s row and column drivers set the required voltage on each subpixel. Processing inside a good monitor takes about a millisecond; in TVs outside game mode it takes tens of milliseconds.

The last step is physics. In an LCD panel the liquid crystals rotate under the electric field and change the polarization of the backlight; a transition from one shade to another takes 1–5 ms on fast panels and up to 10–20 ms on slow ones. An OLED pixel emits light itself, and its response is under 0.1 ms. The model budgets about 4 ms for the output and pixel-transition step.

How long it all takes

Let’s add up the steps of the teaching model: keyboard matrix 1 ms, USB polling 0.5 ms, DMA and interrupt a few tens of microseconds, OS 0.2 ms, program 2 ms, rendering and compositor 3 ms, output to the monitor 4 ms. The total is about 10.7 ms, which is close to the best you can get on a modern computer with a fast monitor.

Real measurements with a high-speed camera show something different: in ordinary editors and terminals 20–70 ms pass from the keypress to the character appearing, and in heavy applications more than 100 ms. The main “time eaters” are not the wires and not the processor, but a program that takes a long time to process the event, a compositor with extra frame buffers, slow processing in the monitor, and waiting for the next frame.

This dispels several misconceptions. “A keyboard with 1,000 Hz polling gives 1 ms of latency”: no, that is only one of ten steps. “Latency is determined by the power of the processor”: almost never; along this path the processor is busy for less than a millisecond in total. “At 60 Hz you can’t notice anything anyway”: people do notice 50 ms of latency when typing, and in games the difference between 20 and 60 ms is palpable.

What is remarkable is something else: in these milliseconds just one bit of information passes through the system, “the A key is pressed,” and yet showing it involves almost every level of this site, from the transistors of the microcontroller to the transistors in every subpixel of the screen. All the stages can be traced in the model at the “Workstation” level.

See also: Workstation: the whole computer

Open on the site →

All articles

Overviews

Logic: from transistor to arithmetic

Processor

Computer

Servers and data centers

Networks and the internet

Software