磁盘调度算法比较差异的c语言算法
时间: 2023-09-01 11:08:48 浏览: 112
好的,下面是五种磁盘调度算法的C语言代码实现和对比:
```c
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void FCFS(int queue[], int head, int n)
{
int seek = 0;
int cur_track;
for (int i = 0; i < n; i++) {
cur_track = queue[i];
seek += abs(cur_track - head);
head = cur_track;
}
printf("FCFS algorithm: Total seek time = %d\n", seek);
}
void SSTF(int queue[], int head, int n)
{
int seek = 0, min, pos;
int cur_track = head;
for (int i = 0; i < n; i++) {
min = INT_MAX;
for (int j = 0; j < n; j++) {
if (abs(queue[j] - cur_track) < min) {
pos = j;
min = abs(queue[j] - cur_track);
}
}
seek += min;
cur_track = queue[pos];
queue[pos] = INT_MAX;
}
printf("SSTF algorithm: Total seek time = %d\n", seek);
}
void SCAN(int queue[], int head, int n)
{
int seek = 0;
int cur_track;
int max_track = queue[n - 1];
for (int i = 0; i < n; i++) {
if (head < queue[i])
break;
seek += abs(head - queue[i]);
head = queue[i];
}
seek += abs(head - 0);
head = 0;
for (int i = 0; i < n; i++) {
if (head < queue[i] && queue[i] <= max_track) {
seek += abs(head - queue[i]);
head = queue[i];
}
}
printf("SCAN algorithm: Total seek time = %d\n", seek);
}
void CSCAN(int queue[], int head, int n)
{
int seek = 0;
int cur_track;
int max_track = queue[n - 1];
for (int i = 0; i < n; i++) {
if (head < queue[i])
break;
seek += abs(head - queue[i]);
head = queue[i];
}
seek += abs(head - 0);
head = 0;
for (int i = 0; i < n; i++) {
if (head < queue[i] && queue[i] <= max_track) {
seek += abs(head - queue[i]);
head = queue[i];
}
}
seek += abs(head - max_track);
head = max_track;
for (int i = n - 1; i >= 0; i--) {
if (head >= queue[i])
break;
seek += abs(head - queue[i]);
head = queue[i];
}
printf("CSCAN algorithm: Total seek time = %d\n", seek);
}
void SJF(int queue[], int head, int n)
{
int seek = 0, min, pos;
int cur_track = head;
for (int i = 0; i < n; i++) {
min = INT_MAX;
for (int j = 0; j < n; j++) {
if (queue[j] != INT_MAX && abs(queue[j] - cur_track) < min) {
pos = j;
min = abs(queue[j] - cur_track);
}
}
seek += min;
cur_track = queue[pos];
queue[pos] = INT_MAX;
}
printf("SJF algorithm: Total seek time = %d\n", seek);
}
int main()
{
int queue[] = { 86, 1470, 913, 1774, 948, 1509, 1022, 1750, 130 };
int head = 143;
int n = sizeof(queue) / sizeof(queue[0]);
FCFS(queue, head, n);
SSTF(queue, head, n);
SCAN(queue, head, n);
CSCAN(queue, head, n);
SJF(queue, head, n);
return 0;
}
```
以上代码中包含了五种不同的磁盘调度算法的实现,可以通过修改队列和磁头的初始位置来进行测试。不同算法之间的差异主要在于对磁道的访问顺序不同,因此在实际应用中需要根据实际情况选择最优的算法。
阅读全文