In a single-cycle processor every instruction takes one clock cycle, so the clock period must be long enough for the slowest instruction.
What to build
A program that computes the delay of each instruction type, the clock period and the total run time of a program.
Requirements
- The input gives five delays in picoseconds: instruction fetch, register read, ALU, data memory, register write.
adduses fetch, register read, ALU and register write.lwuses all five.swuses fetch, register read, ALU and data memory.bequses fetch, register read and ALU.- Print
add D,lw D,sw Dandbeq Dwith each instruction's delay, thenclock C(the largest delay), thenslowest NAME(the first of the four with that delay in the order add, lw, sw, beq). - The second input line gives how many add, lw, sw and beq instructions a program has. Print
total Twith T = clock × the total instruction count.
Input
Two lines: five delays, then four counts.
Output
Seven lines.
Constraints
Delays are whole numbers from 1 to 2000; counts are from 0 to 10⁶.
Example
Input:
200 100 200 200 100
50 20 10 20
Output:
add 600
lw 800
sw 700
beq 500
clock 800
slowest lw
total 80000
Why it works
With one cycle per instruction the clock cannot be shorter than the longest path, even for instructions that finish early. That waste is the main reason why real processors use pipelines.
Examples
200 100 200 200 100 50 20 10 20
add 600 lw 800 sw 700 beq 500 clock 800 slowest lw total 80000
100 100 100 100 100 1 1 1 1
add 400 lw 500 sw 400 beq 300 clock 500 slowest lw total 2000
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
The path of add is fetch + register read + ALU + register write; the others add or drop the memory and write-back steps.
Hint 2
The clock must fit the slowest instruction: take the maximum of the four path delays.
Hint 3
Total time = clock period × total number of instructions, because every instruction takes one whole cycle.
Solution
Show one correct solution (try it yourself first)
f, r, a, m, w = map(int, input().split())
counts = list(map(int, input().split()))
delays = {"add": f + r + a + w, "lw": f + r + a + m + w, "sw": f + r + a + m, "beq": f + r + a}
for name, d in delays.items():
print(name, d)
clock = max(delays.values())
print("clock", clock)
print("slowest", next(k for k, v in delays.items() if v == clock))
print("total", clock * sum(counts))
▶ Open this solution in the compiler, then press Visualize to watch it run step by step