Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Name:- CM Nirmal Reg No:RA2112703010011

Date:-4/11/22 Exp No:11


LRU AND LFU PAGE REPLACEMENT ALGORITHM
AIM : -
To implement LRU and LFU Page Replacement Algorithm using python coding language
and c++ language in ubuntu terminal.

Description of the exercise: -


LRU PAGE REPLACEMENT ALGORITHM
The LRU page replacement algorithm keeps track of the usage of pages over a defined-time
window. When its time to replace a page, it replaces the pages that is least recently used.
LFU PAGE REPLACEMENT ALGORITHM
The LFU page replacement algorithm stands for the Least Frequently Used . In the LFU Page
Replacement Algorithm, the page with the least visits in a given period of time is removed. It
replaces the least frequently used pages. If the frequency of pages remains constant, the page
that comes first is replaced first.

CODE: -
LRU: -
# memory's capacity to hold pages
size = 3
reference_string = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1]
# creating a list to store the current pages in memory
pages = []
# page faults
faults = 0
# page hits
hits = 0
# iterating the reference string
for ref_page in reference_string:
# if a ref_page already exists in pages list, remove it and append it at the end
if ref_page in pages:
pages.remove(ref_page)
pages.append(ref_page)
# incrementing the page hits
hits += 1
# if ref_page is not in the pages list
else:
# incrementing the page faults
faults +=1
# check length of the pages list. If length of pages list
# is less than memory size, append ref_page into pages list
if(len(pages) < size):
pages.append(ref_page)
# if length of pages list is greater than or equal to memory size,
# remove first page of pages list and append new page to pages
else:
pages.remove(pages[0])
pages.append(ref_page)
# printing the number of page hits and page faults
print("Total number of Page Hits:", hits)
print("Total number of Page Faults:", faults)
LFU: -
#include <bits/stdc++.h>
using namespace std;
int pageFaults(int n, int c, int pages[])
{
int count = 0;
vector<int> v;
unordered_map<int, int> mp;
int i;
for (i = 0; i <= n - 1; i++) {
auto it = find(v.begin(), v.end(), pages[i]);
if (it == v.end()) {
if (v.size() == c) {
mp[v[0]]--;
v.erase(v.begin());
}
v.push_back(pages[i]);
mp[pages[i]]++;
count++;
}
else {
mp[pages[i]]++;
v.erase(it);
v.push_back(pages[i]);
}
int k = v.size() - 2;
while (mp[v[k]] > mp[v[k + 1]] && k > -1) {
swap(v[k + 1], v[k]);
k--;
}
}
return count;
}
int main()
{
int pages[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 };
int n = 14, c = 5;
cout << "Page Faults = " << pageFaults(n, c, pages)<< endl;
cout << "Page Hits = " << n - pageFaults(n, c, pages);
return 0;
}
Output: -
LRU: -

LFU: -

RESULT: -
From this experiment we learn about LRU and LFU page replacement algorithm using
python and c++ programming language in ubuntu terminal and also know about Belady’s
Anomaly and number of page faults and number of hits.

You might also like