操作系统作业:实现FCFS调度算法并用文件的方式读取进程信息和输出进程执行顺序,因为不要求使用的语言,所以就用我最喜欢的Python来写:
算法比较简单,以下是源码:
import ast
f = open("C:\\ff.txt","r")
ff = f.read()
str1 = ff.replace("\n"," ")
list = str1.split(" ")
#print(str)
#print(list)
gettime = [] #到达时间
length = len(list)/3
#print(length)
for i in range(0,int(length)):
gettime.append(list[1+3*i])
gettime.sort() #排序
#print(gettime) -> 到达时间
runtime = []
queue = []
liststr = list
for i in range(0,len(gettime)):
s1 = liststr.index(gettime[i])
s = s1-1
queue.append(liststr[s])
liststr[s1] = "ss" #每拿出一个 替换字符 防止重复
#print(liststr)
#print(queue) -> 进程序号
for i in range(0,len(queue)):
#print(list.index(queue[i]))
indexoflist = list.index(queue[i])+2
runtime.append(list[indexoflist])
#print(runtime) -> 运行时间
endtime = []
endtime.append(ast.literal_eval(gettime[0])+ast.literal_eval(runtime[0]))
#print(endtime)
for i in range(1,len(runtime)):
if(endtime[i-1]>ast.literal_eval(gettime[i])):
endtime.append(endtime[i-1]+ast.literal_eval(runtime[i]))
else:
endtime.append(ast.literal_eval(gettime[i])+ast.literal_eval(runtime[i]))
#print(endtime[3])
#计算周转时间
turnovertime = []
for i in range (0,len(endtime)):
turnovertime.append(endtime[i]-ast.literal_eval(gettime[i]))
#print(turnovertime)
sum = 0
for i in range(0,len(turnovertime)):
sum += turnovertime[i]
#print(sum/len(turnovertime))
pj_turnovertime = round(sum/len(turnovertime),3)
#print(pj_turnovertime)
summ = 0
for i in range(0,len(turnovertime)):
summ = summ + (turnovertime[i]/ast.literal_eval(runtime[i]))
dq_turnovertime = round(summ/len(turnovertime),3)
#print(dq_turnovertime)
#print(summ/len(turnovertime))
with open("fcfs.txt","w") as ff:
ff.write("\n进程执行顺序:\n")
for each in queue:
ff.write(" "+ each)
ff.write("\n")
ff.write("\n平均周转时间:\n"+str(pj_turnovertime)+"\n")
ff.write("\n带权周转时间:\n"+str(dq_turnovertime)+"\n")
f.close()
ff.close()