Moving data to or from a device can cost the CPU very different amounts of work, depending on the method.
What to build
A program that compares the CPU cycles of polling, interrupts and DMA for one transfer.
Requirements
- The transfer has n bytes, moved in words of w bytes (the last word may be partly filled). Let words = n ÷ w, rounded up.
- Polling costs
words × c1cycles, interrupts costwords × c2cycles, and DMA costs a fixedscycles. - Print
polling X,interrupts Yanddma Z, thenbest NAMEwith the cheapest method (the first of polling, interrupts, dma on a tie).
Input
One line: n, w, c1, c2, s (whole numbers).
Output
Four lines.
Constraints
1 ≤ n ≤ 10⁷; 1 ≤ w ≤ 64; costs from 0 to 10⁶.
Example
Input:
4096 4 20 100 2000
Output:
polling 20480
interrupts 102400
dma 2000
best dma
Why it works
Polling and interrupts make the CPU handle every word, so their cost grows with the transfer; DMA does the copying itself, so the CPU pays only for the setup and the final interrupt.
Examples
4096 4 20 100 2000
polling 20480 interrupts 102400 dma 2000 best dma
8 4 5 50 1000
polling 10 interrupts 100 dma 1000 best polling
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The number of words is ceil(n ÷ w): use -(-n // w) or (n + w - 1) // w.
Hint 2
Polling and interrupts both cost per word; DMA costs one fixed amount.
Solution
Show one correct solution (try it yourself first)
n, w, c1, c2, s = map(int, input().split())
words = (n + w - 1) // w
costs = [("polling", words * c1), ("interrupts", words * c2), ("dma", s)]
for name, c in costs:
print(name, c)
print("best", min(costs, key=lambda x: x[1])[0])
▶ Open this solution in the compiler, then press Visualize to watch it run step by step