Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Optimal Page Replacement in C++

Optimal Page Replacement in C++

Optimal Page Replacement

The operating system memory is divided into segments. These segments are commonly known as pages. These pages are kept in the main memory and are replaced as per the demands in the operating system. The approach is also known as the page swapping.

Programming Code for Optimal Page Replacement in C++

// Program to calculate the optimal page replacement in C++
#include <bits/stdc++.h>
using namespace std;
// Method to check the availability of a page in the frame bool search(int k, vector& frame) { for (int i = 0; i < frame.size(); i++) if (frame[i] == k) return true; return false; } // Method to identify frame which is least recently used int predict(int pages[], vector& frame, int p_number, int index) { //To store the index of the pages which will be most recently used int recent = -1, last = index; for (int i = 0; i < frame.size(); i++) { int j; for (j = index; j < p_number; j++) { if (frame[i] == pages[j]) { if (j > last) { last = j; recent = i; } break; } } // returning the page which will never be used in the near future if (j == p_number) return i; } // if all the frames will not be used in the future, the code returns them all. Otherwise, the code returns res. return (recent == -1) ? 0 : recent; } void optimalPage(int pages[], int p_number, int fn) { // Creating an array of the given number of frames and initializing it. vector fr;
// Code to traverse through the page reference to check miss and hit. int hit = 0; for (int i = 0; i < p_number; i++) { // Hit is incremented if page is found if (search(pages[i], fr)) { hit++; continue; } // Miss incremented if page not found // Code to check the space available in the frames. if (frame.size() < fn) frame.push_back(pg[i]); // Identify the pages that needs replacement. else { int j = predict(pages, fr, p_number, i + 1); frame[j] = pg[i]; } } cout << "No. of hits = " << hit << endl; cout << "No. of misses = " << p_number - hit << endl; } // Main function int main() { int pg[] = { 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2 }; int pn = sizeof(pg) / sizeof(pg[0]); int fn = 4; optimalPage(pages, p_number, fn); return 0; }

Output

No. of hits = 7
No. of misses = 6