您的位置:首页 > 编程语言 > Python开发

Python - 操作系统FIFO、LRU算法缺页率计算

2017-07-11 23:39 696 查看
操作系统课程作业代码
from math import *
from random import *
from time import clock
import sys

try:
#生成随机序列
def stream(n,m):
stm = []
for i in range(n):
stm.append(randint(0,m))
print("输入流为:"+str(stm))
return stm

#返回去重序列
def uniquelist(lst):
newlist = []
for i in lst:
if i not in newlist:
newlist.append(i)
return newlist

#LRU算法
def LRU(b,stm):
lst = []
count = 0
index = 0
for s in stm:
if s in lst:
index +=1
print(s , ' ', lst)
continue          #如果在物理块中,不缺页
else:
if len(lst)<b:
lst.append(s)
else:
lstb = stm[:index]    #反之,将所求数据流中前第b个非重复值置换出来
lstb = lstb[::-1]
lstb = uniquelist(lstb)
lstb[b-1]= s
lst = lstb[:b]
print(s , ' ', lst , '缺页')
count += 1
index += 1
print("LRU算法缺页率为:{:.5f}".format(count/len(stm)))

#time+1
def timeadd1(lst):
tranlist = []
for i in lst[1::2]:
i += 1
tranlist.append(i)
lst[1::2] = tranlist
return lst

#FIFO算法
def FIFO(b,stm):
lst = []
count = 0
for s in stm:
if s in lst[::2]:
lsta = lst[::2]
lst[lsta.index(s)*2+1] += 1
print(s , ' ', lst[::2])
continue          #如果在物理块中,不缺页
else:
lstb = lst[1::2]

if len(lst)< 2*b:
lst.append(s)
timeadd1(lst)
lst.append(1)
else:
c = lstb.index(max(lstb))
lst[2*c] = s
timeadd1(lst)
lst[2*c+1] = 1
print(s , ' ', lst[::2] , '缺页')
count += 1
print("FIFO算法缺页率为:{:.5f}".format(count/len(stm)))

#主函数
def main():
n = eval(input("Enter the length of input stream:"))        #n = 输入流的长度,由用户输入
m = eval(input("Enter the range of the input stream(0-m):"))#m = 输入流的范围,由用户输入,即范围为0-m之间
b = eval(input("Enter the block size:"))                    #b = 物理块的大小,由用户输入
print("物理块大小为:%d"%b)                                 # 打印物理块的大小
stm = stream(n,m)                                           # 调用stream()函数生成输入流
t1 = clock()
FIFO(b,stm)                                                 #调用FIFO()函数计算FIFO算法的缺页率
print("FIFO算法用时为:{:.5f}".format(clock()-t1))           #打印FIFO算法大概用时
t2 = clock()
LRU(b,stm)                                                  #调用LRU()函数计算LRU算法的缺页率
print("LRU算法用时为:{:.5f}".format(clock()-t2))

#测试函数
def test():
n = 30
m = 9
b = 3
stm = [1,2,5,6,8,3,6,5,3,6,5,6,8,9,2,7,0,4,9,5,3,6,7,4,5,8,7,3,4,5]
print("物理块大小为:%d"%b)
print(stm)
FIFO(b,stm)
LRU(b,stm)

#调用主函数
if __name__ == '__main__':
main()

except:
print ("Unexpected error:", sys.exc_info() )# sys.exc_info()返回出错信息

效果为:



当时还用py2exe模块封装成exe格式,py2exe仅支持Python2.X,具体使用自行摸索
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  操作系统 算法