Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

The Three I/O Methods - Polling, Interrupt, DMA

The Three I/O Methods -- Polling, Interrupt, DMA

In the last lecture we learned how the CPU and memory communicate over the bus. But a computer is not just CPU plus memory - it also needs to exchange data with keyboards, mice, disks, network cards, and other external devices (I/O devices).

The CPU has three basic ways to exchange data with external devices: polling (Polling), interrupt (Interrupt), and DMA (Direct Memory Access). Their efficiencies differ enormously - the choice often determines the performance of the whole system.

This lecture uses three everyday scenarios to build your intuition, then uses Python code to visually compare the efficiency of the three methods.


Three everyday-scenario analogies

Scenario 1: Polling - go check every 5 seconds whether the water has boiled

You are boiling water in the kitchen, but the kettle has no whistle. Every 5 seconds you run from the living room to the kitchen to take a look: "Is it boiling? Is it boiling? Is it boiling?"

During this time you cannot watch TV in peace, because you have to run over every few seconds. You spend almost all your time on "checking status".

This is polling: the CPU keeps looping to check whether a device is ready, wasting time on meaningless queries.

Scenario 2: Interrupt - turn off the stove only when the kettle whistle blows

This time the kettle has a whistle. After you put the water on the stove, you go back to the living room and watch TV in peace. The water boils, the whistle shrills. You pause the TV, go turn off the stove, then go back to watching TV.

You spend the vast majority of your time doing something meaningful (watching TV), interrupted only briefly at the critical moment.

This is interrupt: the CPU executes the program normally, and the device actively sends a signal to notify the CPU when ready. The CPU pauses its current work, handles the device data, then resumes its previous work.

Scenario 3: DMA - just hire a moving company, you do not lift a finger

You are moving house and have a whole truck of furniture to move from the old house to the new one. If you carried it piece by piece yourself (interrupt method), you would have to make dozens of round trips.

You hire a moving company (the DMA controller) and tell them: "the old house address is X, the new house address is Y, there are Z pieces of furniture in total." Then you go on with your own business. Once the movers finish everything, they give you a call saying "done".

This is DMA: a dedicated DMA controller directly manages data transfer between memory and peripherals, with no CPU involvement at all. Only after the transfer completes does the DMA controller send the CPU an interrupt notification.


The essential differences among the three methods

Feature Polling (Polling) Interrupt (Interrupt) DMA
CPU involvement Busy the whole time, checking constantly Briefly involved during transfer Hardly involved, only receives a completion notice
Who moves the data The CPU moves every byte itself The CPU moves every byte itself The DMA controller moves it, the CPU does not care
CPU idle time Almost none Idle most of the time Idle almost all the time
Implementation complexity Simplest Requires interrupt-controller hardware Requires DMA-controller hardware
Response latency Depends on the polling interval Microsecond level Depends on the total DMA transfer duration
Suitable data volume Very small amount Small to medium (KB scale) Large amount (MB/GB scale)
Typical scenario Simple embedded systems, very short waits Keyboard input, mouse movement, network packet arrival Disk reads/writes, graphics framebuffer, large NIC packets

Every keystroke you make triggers an interrupt, and copying a large file uses DMA. Modern operating systems automatically choose the best scheme among the three based on data volume and scenario.


Timeline visualization: a comparison of CPU busy vs idle

Suppose we need to read 4 data blocks from disk into memory. We use an ASCII timeline to visually compare the CPU state under the three methods:



任务: 从硬盘读取 4 个数据块到内存



【轮询 - CPU 几乎全程忙碌】

时间: 0----1----2----3----4----5----6----7----8----9----10--->

CPU:  [查][查][搬][查][查][搬][查][查][搬][查][查][搬]

       忙  忙  忙  忙  忙  忙  忙  忙  忙  忙  忙  忙

                                   ↑ 几乎没有任何空闲



【中断 - CPU 大部分时间空闲】

时间: 0----1----2----3----4----5----6----7----8----9----10--->

CPU:  [工作][等待...][搬][工作]  [等待...][搬][工作]

       忙    闲       忙  忙      闲       忙  忙

                    ↑ 中断触发    ↑ 中断触发



【DMA - CPU 几乎全程空闲】

时间: 0----1----2----3----4----5----6----7----8----9----10--->

CPU:  [设置DMA][工作][工作][工作]      [被通知完成]

       忙       忙    忙    忙              忙

DMA:         [搬][搬][搬][搬]                  ↑ DMA 完成后中断

             忙  忙  忙  忙

                                  ↑ CPU 完全不管传输过程

At a glance: under polling the CPU is tied up, under interrupt the CPU is only briefly interrupted, and under DMA the CPU is almost completely freed.


Code demo: Python simulates the three I/O methods and prints the timeline

The code below uses polling, interrupt, and DMA to simulate the transfer of the same batch of data, tallies the proportion of CPU busy/idle time, and uses a character-based timeline to visually show the difference.

Example

"""
Comparison of the three I/O methods: Polling vs Interrupt vs DMA (runoob demo)

This program simulates the CPU transferring 10 data blocks from an "external device" into memory,
using polling, interrupt, and DMA respectively, and prints a timeline to visually compare CPU states.

Core metric: proportion of CPU busy time. The higher the proportion, the more severely the CPU is dragged down by I/O.
"""

import

time

import

random

class

IODevice:

   

"""Simulate an external I/O device (such as disk, keyboard, etc.)"""

   

def

init

(

self

,

name

=

"Hard disk"

,

response_time

=

4

)

:

       

"""
        name: device name
        response_time: number of "time units" the device needs to respond
        """

       

self

.

name

=

name

       

self

.

response_time

=

response_time  

Device preparation time for each data block

       

self

.

data_buffer

=

[

]

             

Device internal data buffer

       

self

.

ready

=

False

                 

Whether the device is ready

   

def

prepare_data

(

self

,

block_id

)

:

       

"""
        Device prepares data - simulates the device's internal processing.
        In real hardware this step is disk seek, NIC packet reception, and the like.
        """

       

self

.

ready

=

False

        data

=

f

"DATA_BLOCK_{block_id:02d}"

       

self

.

data_buffer

.

append

(

data

)

       

Simulate the device becoming ready after a number of time units

       

return

data

   

def

is_ready

(

self

)

:

       

"""CPU checks this state when polling"""

       

return

self

.

ready

   

def

mark_ready

(

self

)

:

       

"""Device finishes preparation, sends an interrupt signal"""

       

self

.

ready

=

True

   

def

get_data

(

self

)

:

       

"""Take one data block from the device buffer"""

       

if

self

.

data_buffer

:

           

return

self

.

data_buffer

.

pop

(

0

)

       

return

None

class

Timeline:

   

"""
    Timeline recorder - records the CPU and DMA state at each time unit
    Used to finally draw the ASCII timeline
    """

   

def

init

(

self

)

:

       

self

.

cpu_states

=

[

]

   

CPU state at each time unit: 'BUSY' or 'IDLE'

       

self

.

dma_states

=

[

]

   

DMA state at each time unit

       

self

.

events

=

[

]

       

Event log: (time, description)

   

def

record_cpu

(

self

,

state

)

:

       

self

.

cpu_states

.

append

(

state

)

   

def

record_dma

(

self

,

state

)

:

       

self

.

dma_states

.

append

(

state

)

   

def

log_event

(

self

,

time_unit

,

desc

)

:

       

self

.

events

.

append

(

(

time_unit

,

desc

)

)

   

def

draw

(

self

,

title

=

"Timeline"

)

:

       

"""Draw the ASCII timeline"""

        total

=

len

(

self

.

cpu_states

)

       

if

total

==

0

:

           

print

(

" (no time data)"

)

           

return

       

print

(

f

"\n  ╔══ {title} ══╗"

)

       

print

(

f

" ║ Total time units: {total}"

)

       

CPU state line

        cpu_line

=

"CPU:  "

       

for

s

in

self

.

cpu_states

:

            cpu_line +

=

"["

(

"Busy"

if

s

==

"BUSY"

else

"Idle"

)

"]"

       

print

(

f

"  ║ {cpu_line}"

)

       

DMA state line (if there is DMA activity)

       

if

any

(

s

==

"BUSY"

for

s

in

self

.

dma_states

)

:

            dma_line

=

"DMA:  "

           

for

s

in

self

.

dma_states

:

                dma_line +

=

"["

(

"Busy"

if

s

==

"BUSY"

else

"Idle"

)

"]"

           

print

(

f

"  ║ {dma_line}"

)

       

Event log

       

if

self

.

events

:

           

print

(

f

" ╠══ Event Log ══╣"

)

           

for

t

,

desc

in

self

.

events

:

               

print

(

f

"  ║  T={t}: {desc}"

)

       

Statistics summary

        busy_count

=

sum

(

1

for

s

in

self

.

cpu_states

if

s

==

"BUSY"

)

        idle_count

=

total - busy_count

        busy_pct

=

busy_count / total *

100

if

total

0

else

0

        idle_pct

=

idle_count / total *

100

if

total

0

else

0

       

print

(

f

" ╠══ Statistics ══╣"

)

       

print

(

f

" ║ CPU busy: {busy_count}/{total} ({busy_pct:.0f}%)"

)

       

print

(

f

" ║ CPU idle: {idle_count}/{total} ({idle_pct:.0f}%)"

)

       

print

(

f

"  ╚{'═' * 20}╝"

)

       

return

busy_pct

class

Memory:

   

"""Simulate main memory"""

   

def

init

(

self

)

:

       

self

.

data

=

{

}

   

def

write

(

self

,

addr

,

data

)

:

       

self

.

data

[

addr

]

=

data

   

def

repr

(

self

)

:

       

return

f

"Memory({len(self.data)} data items)"

class

Controller:

   

"""CPU controller - runs the simulation of different I/O methods"""

   

def

init

(

self

)

:

       

self

.

memory

=

Memory

(

)

       

self

.

total_transferred

=

0

   

def

simulate_polling

(

self

,

device

,

block_count

)

:

       

"""
        Polling method simulation:
        The CPU checks whether the device is ready at every time unit.
        If ready, move one data block; otherwise keep checking.
        """

       

print

(

f

"\n{'#'*55}"

)

       

print

(

f

"# Method 1: Polling (Polling)"

)

       

print

(

f

"# Device: {device.name} | Block count: {block_count}"

)

       

print

(

f

"# Strategy: CPU checks device state every time unit"

)

       

print

(

f

"{'#'*55}"

)

        timeline

=

Timeline

(

)

        time_unit

=

0

        blocks_done

=

0

        device_ready_at

=

0

 

At which time unit the device is ready with the next block

       

Initialize: device starts preparing the first data block

        device.

prepare_data

(

0

)

        device_ready_at

=

time_unit + device.

response_time

       

while

blocks_done

<

block_count:

           

CPU checks device state (polling)

            timeline.

record_cpu

(

"BUSY"

)

            timeline.

record_dma

(

"IDLE"

)

           

if

time_unit

=

device_ready_at

and

device.

is_ready

(

)

:

               

Device ready -> CPU moves data

                data

=

device.

get_data

(

)

               

self

.

memory

.

write

(

blocks_done

,

data

)

                timeline.

log_event

(

time_unit

,

f

"CPU moves data block {blocks_done}: {data}"

)

                blocks_done +

=

1

               

self

.

total_transferred

=

1

               

Prepare the next data block (if any)

               

if

blocks_done

<

block_count:

                    device.

prepare_data

(

blocks_done

)

                    device_ready_at

=

time_unit + device.

response_time

           

else

:

               

Device not ready -> CPU made a wasted trip

                timeline.

log_event

(

time_unit

,

                    f

"CPU checks device... {'Ready' if device.is_ready() else 'Not ready'}"

)

           

Device works in background (if in preparation stage)

           

if

time_unit

==

device_ready_at:

                device.

mark_ready

(

)

                timeline.

log_event

(

time_unit

,

"Device preparation complete, data ready"

)

            time_unit +

=

1

       

print

(

f

"\n Transfer complete: {self.total_transferred} data blocks"

)

        busy_pct

=

timeline.

draw

(

"Polling method timeline"

)

       

return

busy_pct

   

def

simulate_interrupt

(

self

,

device

,

block_count

)

:

       

"""
        Interrupt method simulation:
        The CPU spends most of its time executing other tasks (recorded as IDLE),
        and only pauses its current work after receiving an interrupt signal, handles the data transfer, then continues.
        """

       

print

(

f

"\n{'#'*55}"

)

       

print

(

f

"# Method 2: Interrupt (Interrupt)"

)

       

print

(

f

"# Device: {device.name} | Block count: {block_count}"

)

       

print

(

f

"# Strategy: CPU runs tasks normally, device sends an interrupt when ready"

)

       

print

(

f

"{'#'*55}"

)

        timeline

=

Timeline

(

)

        time_unit

=

0

        blocks_done

=

0

        transferred_in_interrupt

=

0

        device_ready_at

=

0

       

Initialization

        device.

prepare_data

(

0

)

        device_ready_at

=

time_unit + device.

response_time

       

while

blocks_done

<

block_count:

           

By default: CPU is executing other tasks (idle)

           

if

time_unit

==

device_ready_at:

               

Device ready, sends an interrupt signal

                device.

mark_ready

(

)

                timeline.

log_event

(

time_unit

,

"Interrupt triggered! Device data ready"

)

               

CPU responds to the interrupt and moves data (during this time the CPU is busy)

                data

=

device.

get_data

(

)

               

for

substep

in

range

(

2

)

:  

Interrupt handling takes 2 time units

                   

if

substep

==

0

:

                        timeline.

record_cpu

(

"BUSY"

)

 

Save the context, enter interrupt handling

                        timeline.

record_dma

(

"IDLE"

)

                        timeline.

log_event

(

time_unit + substep

,

f

"CPU enters interrupt handling"

)

                   

else

:

                        timeline.

record_cpu

(

"BUSY"

)

 

Move data

                        timeline.

record_dma

(

"IDLE"

)

                       

self

.

memory

.

write

(

blocks_done

,

data

)

                        transferred_in_interrupt +

=

1

                        timeline.

log_event

(

time_unit + substep

,

f

"CPU moves data block {blocks_done}: {data}"

)

                        blocks_done +

=

1

               

Interrupt handling complete, CPU resumes its previous work

                timeline.

record_cpu

(

"BUSY"

)

                timeline.

record_dma

(

"IDLE"

)

                timeline.

log_event

(

time_unit +

2

,

"CPU resumes its previous work"

)

                time_unit +

=

3

 

Skip the time taken by interrupt handling

               

Prepare the next block

               

if

blocks_done

<

block_count:

                    device.

prepare_data

(

blocks_done

)

                    device_ready_at

=

time_unit + device.

response_time

               

continue

           

Normal execution phase - CPU handles its own tasks

            timeline.

record_cpu

(

"IDLE"

)

            timeline.

record_dma

(

"IDLE"

)

            timeline.

log_event

(

time_unit

,

"CPU executes other tasks (idle/user program)"

)

            time_unit +

=

1

       

print

(

f

"\n Transfer complete: {self.total_transferred} data blocks"

)

        busy_pct

=

timeline.

draw

(

"Interrupt method timeline"

)

       

return

busy_pct

   

def

simulate_dma

(

self

,

device

,

block_count

)

:

       

"""
        DMA method simulation:
        The CPU configures the DMA controller only once at the start, then completely ignores the data transfer.
        The DMA controller moves all data blocks on its own.
        After the transfer completes, DMA sends an interrupt to notify the CPU.
        """

       

print

(

f

"\n{'#'*55}"

)

       

print

(

f

"# Method 3: DMA (Direct Memory Access)"

)

       

print

(

f

"# Device: {device.name} | Block count: {block_count}"

)

       

print

(

f

"# Strategy: CPU continues working after configuring DMA, DMA controller moves data automatically"

)

       

print

(

f

"{'#'*55}"

)

        timeline

=

Timeline

(

)

        time_unit

=

0

        dma_busy_until

=

0

        setup_done

=

False

        blocks_to_transfer

=

list

(

range

(

block_count

)

)

        dma_buffer

=

[

]

       

Prepare all data blocks

       

for

i

in

range

(

block_count

)

:

            device.

prepare_data

(

i

)

       

while

blocks_to_transfer

or

dma_buffer:

           

Phase 1: CPU configures the DMA controller (only once, taking 2 time units)

           

if

not

setup_done:

               

for

substep

in

range

(

2

)

:

                    timeline.

record_cpu

(

"BUSY"

)

                    timeline.

record_dma

(

"IDLE"

)

                   

if

substep

==

0

:

                        timeline.

log_event

(

time_unit

,

                           

"CPU configures DMA: set source address, destination address, transfer byte count"

)

                   

else

:

                        timeline.

log_event

(

time_unit

,

                           

"CPU starts the DMA transfer, then continues its own work"

)

                    time_unit +

=

1

                setup_done

=

True

                dma_busy_until

=

time_unit + block_count * device.

response_time

               

Mark the device as ready

                device.

mark_ready

(

)

               

Pre-fill the DMA buffer

               

while

device.

data_buffer

:

                    dma_buffer.

append

(

device.

data_buffer

.

pop

(

0

)

)

               

continue

           

Phase 2: DMA controller moves data on its own, CPU is idle

           

if

time_unit

<

dma_busy_until:

                timeline.

record_cpu

(

"IDLE"

)

                timeline.

record_dma

(

"BUSY"

)

               

if

dma_buffer:

                    data

=

dma_buffer.

pop

(

0

)

                    blocks_to_transfer.

pop

(

0

)

                    mem_addr

=

block_count -

len

(

blocks_to_transfer

)

1

                   

self

.

memory

.

write

(

mem_addr

,

data

)

                   

self

.

total_transferred

=

1

                    timeline.

log_event

(

time_unit

,

f

"DMA moves data block {mem_addr}: {data}"

)

               

else

:

                    timeline.

log_event

(

time_unit

,

"DMA controller working..."

)

           

else

:

               

Phase 3: DMA completes, sends an interrupt to notify the CPU

                timeline.

record_cpu

(

"BUSY"

)

                timeline.

record_dma

(

"BUSY"

)

                timeline.

log_event

(

time_unit

,

"DMA transfer complete, interrupt notifies CPU"

)

                timeline.

record_cpu

(

"BUSY"

)

                timeline.

record_dma

(

"IDLE"

)

                timeline.

log_event

(

time_unit +

1

,

"CPU confirms transfer complete"

)

                time_unit +

=

2

               

break

            time_unit +

=

1

       

print

(

f

"\n Transfer complete: {self.total_transferred} data blocks"

)

        busy_pct

=

timeline.

draw

(

"DMA method timeline"

)

       

return

busy_pct

===== Main program: comparison of the three methods =====

if

name

==

"main"

:

   

print

(

"="

60

)

   

print

(

" I/O three-method efficiency comparison - RUNOOB computer organization demo"

)

   

print

(

"="

60

)

   

print

(

)

   

print

(

"Scenario: transfer 5 data blocks from an external device to memory"

)

   

print

(

"Device response time (time units needed to prepare each data block): 4"

)

   

print

(

)

    BLOCK_COUNT

=

5

    RESPONSE_TIME

=

4

    results

=

{

}

   

---- Method 1: Polling ----

    dev1

=

IODevice

(

"Hard disk"

,

RESPONSE_TIME

)

    ctrl1

=

Controller

(

)

    pct1

=

ctrl1.

simulate_polling

(

dev1

,

BLOCK_COUNT

)

    results

[

"Polling"

]

=

pct1

   

---- Method 2: Interrupt ----

    dev2

=

IODevice

(

"Hard disk"

,

RESPONSE_TIME

)

    ctrl2

=

Controller

(

)

    pct2

=

ctrl2.

simulate_interrupt

(

dev2

,

BLOCK_COUNT

)

    results

[

"Interrupt"

]

=

pct2

   

---- Method 3: DMA ----

    dev3

=

IODevice

(

"Hard disk"

,

RESPONSE_TIME

)

    ctrl3

=

Controller

(

)

    pct3

=

ctrl3.

simulate_dma

(

dev3

,

BLOCK_COUNT

)

    results

[

"DMA"

]

=

pct3

   

---- Final comparison ----

   

print

(

"\n"

"="

60

)

   

print

(

" Comparison of CPU busy time proportion among the three methods"

)

   

print

(

"="

60

)

   

print

(

f

" Polling (Polling): CPU busy {results['Polling']:.0f}% of the time"

)

   

print

(

f

" Interrupt (Interrupt): CPU busy {results['Interrupt']:.0f}% of the time"

)

   

print

(

f

" DMA: CPU busy {results['DMA']:.0f}% of the time"

)

   

print

(

)

    best

=

min

(

results

,

key

=

results.

get

)

    worst

=

max

(

results

,

key

=

results.

get

)

   

print

(

f

" Best method: {best} (least CPU usage)"

)

   

print

(

f

" Worst method: {worst} (most CPU usage)"

)

   

print

(

)

   

print

(

f

" Conclusion: for large data transfers, DMA reduces CPU usage compared with polling by"

)

   

print

(

f

" about {results['Polling'] - results['DMA']:.0f} percentage points."

)

   

print

(

f

" This is why modern computers use DMA when transferring large files."

)

   

print

(

"="

60

)


Real-world application scenarios

Keyboard input - a typical example of interrupt

Every time you press a key, the keyboard controller sends the CPU an interrupt signal. The CPU pauses the current program, reads the key code, then resumes. This process is so fast that you notice no delay at all.

If the keyboard used polling - the CPU checking 1000 times per second "has the user pressed a key?" - your computer would freeze and be unable to do anything else.

Large file copy - a typical example of DMA

You copy a 2GB movie from drive C to drive D. The disk controller moves data directly into memory via DMA, with almost no CPU involvement the whole time. You can still browse the web and write code, completely unaffected.

Without DMA - the CPU would have to move the 2GB of data itself - during which time the CPU basically cannot handle any other task.

Why has polling not been eliminated?

Although polling is the least efficient, it is still useful in extremely simple embedded systems:


Summary and check

In one sentence:Polling is the CPU constantly asking "ready yet?", interrupt is the device actively shouting "I am ready!", and DMA is finding a helper to do the work for you - the larger the data volume, the more obvious DMA's advantage.

Self-test questions

  1. You are writing a document on the computer while a large file is being copied in the background. Which I/O method does the file copy use? Which one do you use when typing on the keyboard?
  2. If a device's data preparation time is extremely short (say only 1 microsecond), would polling still waste the CPU? Why?
  3. After the DMA controller completes a data transfer, how does it notify the CPU? What mechanism does it use?

Reference answers: 1. File copy uses DMA, keyboard input uses interrupt. 2. It still wastes - because during polling the CPU cannot do other things; even if each poll is fast, the occupied time slices cannot be used to run user programs. But if the device is truly very fast, polling's implementation simplicity may be more advantageous. 3. After DMA completes, it notifies the CPU via an interrupt - this is the only moment DMA needs CPU involvement.