gpt4 book ai didi

c# - LRU页面置换算法C#

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:47:19 26 4
gpt4 key购买 nike

我正在尝试编写一个模拟 LRU 页面替换的函数。我非常了解 LRU,但在编码时遇到问题。以下内容被传递到 LRU 函数中。用户指定#'s 1-9 的 20 个字符引用字符串,它存储在一个名为 refString 的大小为 20 的数组中。用户输入的帧数 (1-7) 存储在变量 numFrames 中。最后传入一个大小为7的数组frame。

这是我的代码,我得到了一个接近但不完全的数字。也许有人可以帮忙!

private static void LRU(int numFrames, int[] refString, int[] frame)
{
int i, j = 0, k, m, flag = 0, count = 0, top = 0;

for (i = 0; i < 20; i++)
{
for (k = 0; k < numFrames; k++)
{
if (frame[k] == refString[i])
{
flag = 1;
break;
}
}

if (j != numFrames && flag != 1)
{
frame[top] = refString[i];
j++;

if (j != numFrames)
{
top++;
}
}

else
{
if (flag != 1)
{
for (k = 0; k < top; k++)
{
frame[k] = frame[k + 1];
}

frame[top] = refString[i];
}

if (flag == 1)
{
for (m = k; m < top; m++)
{
frame[m] = frame[m + 1];
}

frame[top] = refString[i];
}
}

if (flag == 0)
{
count++;
}
else
{
flag = 0;
}

}

Console.WriteLine("\nThe number of page faults with LRU is: " + count);
}

最佳答案

您的代码中几乎没有错误:-

if (top < numFrames)
{
frame[top++] = refString[i];
fault++;
}

在这里你永远不会检查当前的 refString[i] 是否已经在 frame[] 中,因为在那种情况下你不会出错并且不应该将它添加到 frame 中。

这是一个伪代码,可以帮助您消除疑虑:-

void LRU(int numframes,int refString[],int frames[]) {

int top = 0,fault=0;
int* count = new int[numframes];

for(int i=0;i<refString.length;i++) {

int k = findmax(refString[i],frames,count,top,numframes);

if(k<0) {
count[top] = 0;
frames[top++] = refString[i];
fault++;
}

else if(frames[k]!=refString[i]) {

count[k] = 0;
frames[k] = refString[i];
fault++;

}
else count[k] = 0;

for(int j=0;j<top;j++) {
count[j]++;

}

}

return(fault);

}


int findmax(int keyframe,int frames[],int count,int top,int numframes) {

int max = 0;
for(int i=0;i<top;i++) {

if(frames[i]==keyframe) {

return(i);
}
if(count[max]<count[i])
max = i;

}

if(top<numframes)
return(-1);
return(max);
}

编辑:

伪代码解释:-

1. check if current requested frame is in cache and if yes then get its index
2. if frame is present then set its count to zero so as to indicate it is used very recently, higher the count the more least recently frame is used.
3. if frame is not present in cache then
a. check if cache is full if not add new frame to end of cache and increment the fault and top of cache
b. else if chace is full then get frame with maximum count(LRU frame) and replace it with new frame and reset count to zero and increment fault.
4. increment all the counts
5. do 1 to 4 till end of all requests
6. output the no of faults

关于c# - LRU页面置换算法C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20136696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com