import random
def generate_page_sequence(length, page_range):
return [random.randint(0, page_range - 1) for _ in range(length)]
def fifo(page_sequence, available_frames):
frame_list = []
page_faults = 0
for page in page_sequence:
if page not in frame_list:
page_faults += 1
if len(frame_list) < available_frames:
frame_list.append(page)
else:
frame_list.pop(0)
frame_list.append(page)
return page_faults
def lru(page_sequence, available_frames):
frame_list = []
recent_used = []
page_faults = 0
for page in page_sequence:
if page not in frame_list:
page_faults += 1
if len(frame_list) < available_frames:
frame_list.append(page)
else:
least_recent = min(recent_used, key=recent_used.get)
frame_list.remove(least_recent)
frame_list.append(page)
del recent_used[least_recent]
recent_used[page] = recent_used.get(page, 0) + 1
return page_faults
def main():
random.seed(125)
L = 100 # 页面走向长度
m = 3 # 可用内存块
k = 10 # 页表长度
page_sequence = generate_page_sequence(L, k)
fifo_page_faults = fifo(page_sequence, m)
lru_page_faults = lru(page_sequence, m)
print("页面走向:", page_sequence)
print("FIFO缺页次数:", fifo_page_faults)
print("FIFO缺页率:", fifo_page_faults / L)
print("LRU缺页次数:", lru_page_faults)
print("LRU缺页率:", lru_page_faults / L)
if __name__ == "__main__":
main()