实验作业
先来先服务调度算法。
最短作业优先调度算法。
最高响应比优先调度算法。
#include<bits/stdc++.h> #include <iostream> #include <cstring> #include <cstdio> #include <thread> #include <string> #include <algorithm> using namespace std; const int maxn = 1e5 + 7, inf = 1e9 + 7; struct JOB { string name; int start; int runtime; }x[maxn]; int n, t; bool FCFSsort(JOB a, JOB b) { return a.start < b.start; } bool SJFsort(JOB a, JOB b) { if (a.runtime == b.runtime) return a.start < b.start; return a.runtime < b.runtime; } bool HRRNsort(JOB a, JOB b) { if (t >= a.start || t >= b.start) return (t - a.start) / a.runtime > (t - b.start) / b.runtime; else return a.start > b.start; } void FCFS() { double tat = 0, taw = 0; sort(x, x + n, FCFSsort); cout << "调度过程:\n进程名 运行开始时间 运行结束时间 周转时间" << endl; for (int i = 0, t = 0; i < n; i++) { t = max(x[i].start, t); cout << x[i].name; printf(" %8d %8d %8d\n", t, t + x[i].runtime, t + x[i].runtime - x[i].start); // cout << x[i].name << " " << t << " " << t + x[i].runtime << endl; t += x[i].runtime; tat += (t - x[i].start); taw += (double)(t - x[i].start) / x[i].runtime; } printf("平均周转时间为:%.3f\n平均带权周转时间为:%.3f\n\n", tat / n, taw / n); } void SJF() { double tat = 0, taw = 0; sort(x, x + n, SJFsort); cout << "调度过程:\n进程名 运行开始时间 运行结束时间 周转时间" << endl; for (int i = 0, t = 0; i < n; i++) { if (t < x[i].start)//不中断,在最短作业未进入时,选择较小的已经进入的进程,若无则选择最先进程 { int mint = x[i].start; for (int j = i + 1; j < n; j++) { if (x[j].start < t) { mint = x[j].start; break; } else if (x[j].start < mint) mint = x[j].start; swap(x[i], x[j]); } } t = max(x[i].start, t); cout << x[i].name; printf(" %8d %8d %8d\n", t, t + x[i].runtime, t + x[i].runtime - x[i].start); // cout << x[i].name << " " << t << " " << t + x[i].runtime << endl; t += x[i].runtime; tat += (t - x[i].start); taw += (double)(t - x[i].start) / x[i].runtime; } printf("平均周转时间为:%.3f\n平均带权周转时间为:%.3f\n\n", tat / n, taw / n); } void HRRN() { t = 0; double tat = 0, taw = 0; sort(x, x + n, HRRNsort); cout << "调度过程:\n进程名 运行开始时间 运行结束时间 周转时间" << endl; for (int j = 0, i = 0; j < n; j++) { t = max(x[i].start, t); cout << x[i].name; printf(" %8d %8d %8d\n", t, t + x[i].runtime, t + x[i].runtime - x[i].start); // cout << x[i].name << " " << t << " " << t + x[i].runtime << endl; t += x[i].runtime; tat += (t - x[i].start); taw += (double)(t - x[i].start) / x[i].runtime; x[i].start = inf; sort(x, x + n, HRRNsort); } printf("平均周转时间为:%.3f\n平均带权周转时间为:%.3f\n\n", tat / n, taw / n); } int main() { // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); cout << "需要创建几个进程?" << endl; cin >> n; cout << "请按照以下格式创建进程\n进程名 创建时间 执行时间" << endl; for (int i = 0; i < n; i++) { cin >> x[i].name >> x[i].start >> x[i].runtime; } cout << "创建成功!" << endl << endl; cout << " 先来先服务调度算法(FCFS):" << endl; FCFS(); cout << " 短作业优先调度算法(SJF):" << endl; SJF(); cout << " 高相应比优先调度算法(HRRN):" << endl; HRRN(); } /* 3 1 8 2 2 9 1 3 10 1 */