Skip to content

Instantly share code, notes, and snippets.

@st-tran
Created August 28, 2020 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st-tran/8dd0d5ff677a08410066dbfb145f7ca4 to your computer and use it in GitHub Desktop.
Save st-tran/8dd0d5ff677a08410066dbfb145f7ca4 to your computer and use it in GitHub Desktop.
Clock page replacement algorithm simulator that mimics an exercise in CSC369 (UofT)
import sys
if __name__ == "__main__":
iterations = 0
CLOCK_HAND = 0
FRAMES = int(input("Enter the number of frames in memory/TLB: "))
MEM = [["empty", 0] for i in range(FRAMES)]
print("Now, enter the reference trace (page references). "
"Exit with EOF or empty line (CRLF or LF)")
for data in sys.stdin:
if not data or data == "\n" or data == "\r\n":
break
data = data.strip("\n")
iterations += 1
print(f"Step {iterations}, {data}")
print(CLOCK_HAND)
if any(MEM[i][0] == data for i in range(FRAMES)):
print("Hit")
for i in range(FRAMES):
if MEM[i][0] == data:
MEM[i][1] = 1
else:
first = True
while MEM[CLOCK_HAND][1] != 0:
if first:
first = False
else:
iterations += 1
print(f"Step {iterations}, {data}")
print(CLOCK_HAND)
MEM[CLOCK_HAND][1] = 0
print("Check")
print(" ".join(f"{e[0]}({e[1]})" for e in MEM))
print()
CLOCK_HAND = (CLOCK_HAND + 1) % FRAMES
if not first:
iterations += 1
print(f"Step {iterations}, {data}")
print(CLOCK_HAND)
print("Replace")
MEM[CLOCK_HAND][0] = data
MEM[CLOCK_HAND][1] = 1
CLOCK_HAND = (CLOCK_HAND + 1) % FRAMES
print(" ".join(f"{e[0]}({e[1]})" for e in MEM))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment