请求分页算法 Python实现

本文档展示了操作系统中四种页面置换算法(OPT、FIFO、LRU、Clock)的Python实现,用于模拟请求分页过程。通过用户输入的页面访问序列和物理块数量,计算并比较各算法的缺页次数和缺页率,帮助理解不同页面置换策略的性能差异。
摘要由CSDN通过智能技术生成

操作系统模拟之请求分页算法。
文件共1份,代码如下:

import math
import os
import random
import copy

def alo_opt():
    print("您选择了OPT算法,执行结果如下:")
    print("访问页面  物理块  缺页中断")
    temp_queue = []
    sum_changed = 0
    for i in range(page_size):
        flag_changed = False
        if len(temp_queue) < temp_queue_size and temp_queue.count(page_queue[i]) == 0:
            temp_queue.append(page_queue[i])
        elif temp_queue.count(page_queue[i]) == 0:
            appear_position = []
            for j in range(temp_queue_size):
                appear_position.append(page_size)
            for j in range(i + 1, page_size):
                if temp_queue.count(page_queue[j]) > 0 and appear_position[
                    temp_queue.index(page_queue[j])] == page_size:
                    appear_position[temp_queue.index(page_queue[j])] = j
            remotest_position = appear_position.index(max(appear_position))
            temp_queue[remotest_position] = page_queue[i]
            sum_changed = sum_changed + 1
            flag_changed = True
        output_queue = copy.deepcopy(temp_queue)
        for j in range(temp_queue_size - len(temp_queue)):
            output_queue.append("&")
        print('{}  {}  {}'.format(page_queue[i], output_queue, flag_changed))
    print()
    print('页面访问序列总长{0},OPT算法共发生缺页中断{1}次,缺页率为{1}/{0}'.format(page_size, sum_changed))

def alo_fifo():
    print("您选择的是先进先出页面置换算法")
    print("访问页面  物理块  缺页中断")
    temp_queue = []
    sum_changed = 0
    appear_time = []
    for i in range(page_size+1):
        appear_time.append(page_size)
    for i in range(page_size):
        flag_changed = False
        if len(temp_queue) < temp_queue_size and temp_queue.count(page_queue[i]) == 0:
            temp_queue.append(page_queue[i])
            appear_time[page_queue[i]] = i
        elif temp_queue.count(page_queue[i]) == 0:
            target_index = 0
            min_time = page_size
            for j in range(0, temp_queue_size):
                if appear_time[temp_queue[j]] < min_time:
                    min_time = appear_time[temp_queue[j]]
                    target_index = j
            appear_time[temp_queue[target_index]] = page_size
            temp_queue[target_index] = page_queue[i]
            appear_time[page_queue[i]] = i
            sum_changed = sum_changed + 1
            flag_changed = True
        output_queue = copy.deepcopy(temp_queue)
        for j in range(temp_queue_size - len(temp_queue)):
            output_queue.append("&")
        print('{}  {}  {}'.format(page_queue[i], output_queue, flag_changed))
    print()
    print('页面访问序列总长{0},FIFO算法共发生缺页中断{1}次,缺页率为{1}/{0}'.format(page_size, sum_changed))

def alo_lru():
    print("您选择的是最近最久未使用页面置换算法")
    print("访问页面  物理块  缺页中断")
    temp_queue = []
    sum_changed = 0
    recent_used = []
    for i in range(page_size+1):
        recent_used.append(0)
    for i in range(page_size):
        flag_changed = False
        if len(temp_queue) < temp_queue_size and temp_queue.count(page_queue[i]) == 0:
            temp_queue.append(page_queue[i])
        elif temp_queue.count(page_queue[i]) == 0:
            target_index = 0
            min_time = page_size
            for j in range(0, temp_queue_size):
                if recent_used[temp_queue[j]] < min_time:
                    min_time = recent_used[temp_queue[j]]
                    target_index = j
            temp_queue[target_index] = page_queue[i]
            recent_used[page_queue[i]] = i
            sum_changed = sum_changed + 1
            flag_changed = True
        else:
            recent_used[page_queue[i]] = i
        output_queue = copy.deepcopy(temp_queue)
        for j in range(temp_queue_size - len(temp_queue)):
            output_queue.append("&")
        print('{}  {}  {}'.format(page_queue[i], output_queue, flag_changed))
    print()
    print('最近最久未使用页面置换算法缺页{0}次, 缺页率为{0}/{1}'.format(sum_changed, page_size))

def alo_clock():
    print("您选择的是时钟页面置换算法")
    print("访问页面  物理块  缺页中断")
    temp_queue = []
    sum_changed = 0
    flag = {}
    for i in range(0, page_size+1):
        flag[i] = False
    point = 0
    for i in range(page_size):
        flag_changed = False
        if len(temp_queue) < temp_queue_size and temp_queue.count(page_queue[i]) == 0:
            temp_queue.append(page_queue[i])
            flag[page_queue[i]] = True
            point = temp_queue.index(page_queue[i]) + 1
        elif temp_queue.count(page_queue[i]) == 1:
            point = temp_queue.index(page_queue[i])
            flag[page_queue[i]] = True
        elif temp_queue.count(page_queue[i]) == 0:
            while True:
                if not flag[temp_queue[point % temp_queue_size]]:
                    temp_queue[point % temp_queue_size] = page_queue[i]
                    point = point + 1
                    sum_changed = sum_changed + 1
                    flag_changed = True
                    break
                else:
                    flag[temp_queue[point % temp_queue_size]] = False
                    point = point + 1
        output_queue = copy.deepcopy(temp_queue)
        for j in range(len(temp_queue)):
            if flag[temp_queue[j]]:
                output_queue[j] = str(temp_queue[j]) + "*"
        for j in range(temp_queue_size - len(temp_queue)):
            output_queue.append("&")
        print('{}  {}  {}'.format(page_queue[i], output_queue, flag_changed))
    print()
    print('时钟页面置换算法缺页{0}次, 缺页率为{0}/{1}'.format(sum_changed, page_size))


print("欢迎进入操作系统课程演示系统之页面置换算法!")
print()

flag_exit = False
while True:
    if flag_exit == True:
        print("您已成功退出系统!")
        break
    print("请输入页面访问序列长度(15-25,含端点):")
    while True:
        page_size = int(input())
        if page_size >= 15 and page_size <= 25:
            break
        print("您输入的页面访问序列长度超出给定范围,请重新输入15-25(含端点)的数字:")
    print("请输入物理块个数(3-5,含端点):")
    while True:
        temp_queue_size = int(input())
        if temp_queue_size >= 3 and temp_queue_size <= 5:
            break
        print("您输入的物理块个数超出给定范围,请重新输入3-5(含端点)的数字:")
    print()
    page_queue = []
    print("选择用户输入请输入1")
    print("选择随机生成请输入2")
    data_produce_choice = int(input())
    if data_produce_choice == 2:
        for i in range(page_size):
            page_queue.append(random.randint(0, 5))
    else:
        while True:
            print('请输入0-5数字组成的无规律字符串作为页面访问序列,长度为{}'.format(page_size))
            flag_digit = True
            temp = input().split(" ")
            key = ["0", "1", "2", "3", "4", "5"]
            for i in temp:
                if key.count(i) == 0:
                    flag_digit = False
            if not flag_digit:
                print("您输入的序列有误,请重新输入")
            elif len(temp) < page_size:
                print('您已输入{}长度的字符串,还需输入{}长度的字符串'.format(len(temp), page_size - len(temp)))
                print('请继续输入0-5数字组成的无规律字符串作为页面访问序列,长度为{}'.format(page_size - len(temp)))
                temp_plus = input().split(" ")
                if len(temp_plus) != page_size - len(temp):
                    print("您再次输入错误,序列需要全部重新输入")
                    continue
                for i in temp:
                    page_queue.append(int(i))
                for i in temp_plus:
                    page_queue.append(int(i))
            elif len(temp) > page_size:
                print("您输入的字符串超长,系统将进行自动截取Y或由用户重新输入N(Y/N)")
                if input() == "Y":
                    for i in range(page_size):
                        page_queue.append(int(temp[i]))
                    break
                else:
                    continue
            else:
                for i in temp:
                    page_queue.append(int(i))
                break
    print()
    print('页面访问序列为:{}'.format(page_queue))
    print('物理块个数为:{}'.format(temp_queue_size))
    print()
    while True:
        print("选择最佳置换算法请输入1")
        print("选择先进先出页面置换算法请输入2")
        print("选择最近最久未使用页面置换算法请输入3")
        print("选择时钟页面置换算法请输入4")
        menu_choice = int(input())
        if menu_choice == 1:
            alo_opt()
        elif menu_choice == 2:
            alo_fifo()
        elif menu_choice == 3:
            alo_lru()
        elif menu_choice == 4:
            alo_clock()
        else:
            print("您的算法选择错误,请重新输入!")

        print()
        print("继续尝试其他算法请输入1")
        print("更换数据请输入2")
        print("退出程序请输入3")
        end_choice = int(input())
        if end_choice == 2:
            break
        elif end_choice == 3:
            flag_exit = True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值