void FIFO_solve()
{
memset(in, 0, sizeof(in));
int fault_n = 0; //缺页次数
int ptr, i;
//预调页填满内存
ptr = 0; //下一个要存放的位置
for (i = 0; i < maxn && ptr < size; i++)
if (!in[page[i]])
{
pin[ptr++] = page[i];
in[page[i]] = 1;
fault_n++;
}
//继续执行剩下的指令
ptr = 0; //队列最前面的位置,即最先进来的位置
for (; i < maxn; i++)
if (!in[page[i]])
{
in[pin[ptr]] = 0; //移出最先进入的页面
pin[ptr] = page[i]; //放入新页面
in[page[i]] = 1;
fault_n++;
ptr = (ptr + 1) % size; //模拟循环队列
}
printf("\nBy FIFO algorithm, the fault-page number is: %d\n", fault_n);
printf(" the hit ratio is : %.2lf\n", (1 - (fault_n + 0.0) / 320.0));
}
==================================
void LRU_solve()
{
int ltu[maxp]; //last_time_use
int ti = 1; //模拟时间
int fault_n = 0;
memset(ltu, 0, sizeof(ltu));
memset(in, 0, sizeof(in));
memset(pin, -1, sizeof(pin));
int min, ptr, i, j;
for (i = 0; i < maxn; i++)
{
if (!in[page[i]])
{
//寻找最近最少使用的页面
min = 1000000;
ptr = 0;
for (j = 0; j < size; j++)
{
if (ltu[j] < min)
{
min = ltu[j];
ptr = j;
}
}
//替换或写入
if (pin[ptr] != -1)
in[pin[ptr]] = 0;
pin[ptr] = page[i];
in[page[i]] = 1;
fault_n++;
ltu[ptr] = ti++;
}
else //已经在内存中,更新最近使用时间
{
for (j = 0; j < size; j++)
if (pin[j] == page[i])
{
ltu[j] = ti++;
break;
}
}
}
printf("\nBy LRU algorithm, the fault-page number is: %d\n", fault_n);
printf(" the hit ratio is : %.2lf\n", (1 - (fault_n + 0.0) / 320.0));
}
==========================
void OPT_solve()
{
int ntu[maxp]; //next_time_use
int fault_n = 0;
int i, j;
memset(in, 0, sizeof(in));
memset(ntu, -1, sizeof(ntu));
//预调页填满内存
int ptr = 0;
for (i = 0; i < maxn && fault_n < size; i++)
{
if (!in[page[i]])
{
in[page[i]] = 1;
pin[ptr] = page[i];
fault_n++;
ptr++;
}
}
//初始化ntu数组
ptr = 0;
for (j = i; j < maxn && ptr < 32; j++)
{
if (ntu[page[j]] == -1)
{
ntu[page[j]] = j;
ptr++;
}
}
int temp;
for (; i < maxn; i++)
{
if (!in[page[i]])
{
temp = 0;
ptr = 0;
for (j = 0; j < size; j++)
{
if (ntu[pin[j]] == -1)
{
ptr = j;
break;
}
if (ntu[pin[j]] > temp)
{
temp = ntu[pin[j]];
ptr = j;
}
}
in[pin[ptr]] = 0;
in[page[i]] = 1;
pin[ptr] = page[i];
fault_n++;
}
ntu[page[i]] = -1;
for (j = i + 1; j < maxn; j++)
if (page[j] == page[i])
{
ntu[page[i]] = j;
break;
}
}
printf("\nBy OPT algorithm, the fault-page number is: %d\n", fault_n);
printf(" the hit ratio is : %.2lf\n", (1 - (fault_n + 0.0) / 320.0));
}