0% found this document useful (0 votes)
40 views16 pages

CPU Scheduling Algorithms in C

Uploaded by

tomaramit046
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views16 pages

CPU Scheduling Algorithms in C

Uploaded by

tomaramit046
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INDEX

Experiment 1- Write a program to implement FCFS CPU


scheduling.
#include<stdio.h>
Void findWaitingTime(int processes[], int n, Int bt[], int wt[])
{
Wt[0] = 0;
For (int I = 1; I < n ; i++ )
Wt[i] = bt[i-1] + wt[i-1] ;
}
Void findTurnAroundTime( int processes[], int n, Int bt[], int wt[], int tat[]) {
For (int I = 0; I < n ; i++)
Tat[i] = bt[i] + wt[i];
}
Void findavgTime( int processes[], int n, int bt[]) {
Int wt[n], tat[n], total_wt = 0, total_tat = 0;
findWaitingTime(processes, n, bt, wt);
findTurnAroundTime(processes, n, bt, wt, tat);
printf(“Processes Burst time Waiting time Turn around time\n”);
for (int i=0; i<n; i++) {
Total_wt = total_wt + wt[i];
Total_tat = total_tat + tat[i];
Printf(“ %d “,(i+1));
Printf(“ %d “, bt[i] );
Printf(“ %d”,wt[i] );
Printf(“ %d\n”,tat[i] );
}
Float s=(float)total_wt / (float)n;
Float t=(float)total_tat / (float)n;
Printf(“Average waiting time = %f”,s);
Printf(“\n”);
Printf(“Average turn around time = %f “,t);
}
Int main() {
Int processes[] = { 1, 2, 3};
Int n = sizeof processes / sizeof processes[0];
Int burst_time[] = {10, 5, 8};
findavgTime(processes, n, burst_time);
return 0;
}
OUTPUT-
Experiment 2- Write a program to implement SGF CPU scheduling.
#include<stdio.h>
Int main(){
Int bt[20],p[20],wt[20],tat[20],I,j,n,total=0,totalT=0,pos,temp;
Float avg_wt,avg_tat;
Printf(“Enter number of process:”);
Scanf(“%d”,&n);
Printf(“\nEnter Burst Time:\n”);
For(i=0;i<n;i++) {
Printf(“p%d:”,i+1);
Scanf(“%d”,&bt[i]);
P[i]=i+1;
}
For(i=0;i<n;i++){
Pos=I;
For(j=i+1;j<n;j++){
If(bt[j]<bt[pos])
Pos=j;
}
Temp=bt[i];
Bt[i]=bt[pos];
Bt[pos]=temp;
Temp=p[i];
P[i]=p[pos];
P[pos]=temp;
} Wt[0]=0;
For(i=1;i<n;i++) {
Wt[i]=0;
For(j=0;j<I;j++)
Wt[i]+=bt[j];
Total+=wt[i];
}
Avg_wt=(float)total/n;
Printf(“\nProcess\t Burst Time \tWaiting Time\tTurnaround Time”);
For(i=0;i<n;i++){
Tat[i]=bt[i]+wt[i];
totalT+=tat[i];
printf(“\np%d\t\t %d\t\t %d\t\t\t%d”,p[i],bt[i],wt[i],tat[i]);
} Avg_tat=(float)totalT/n;
Printf(“\n\nAverage Waiting Time=%f”,avg_wt);
Printf(“\nAverage Turnaround Time=%f”,avg_tat);
}
OUTPUT –
Experiment 3- Write a program to implement PRIORITY CPU
scheduling.
#include <stdio.h>
Void swap(int *a,int *b){
Int temp=*a;
*a=*b;
*b=temp;
}Int main(){
Int n;
Printf(“Enter Number of Processes: “);
Scanf(“%d”,&n);
Int burst[n],priority[n],index[n];
For(int i=0;i<n;i++) {
Printf(“Enter Burst Time and Priority Value for Process %d: “,i+1);
Scanf(“%d %d”,&burst[i],&priority[i]);
Index[i]=i+1;
}For(int i=0;i<n;i++){
Int temp=priority[i],m=I;
For(int j=I;j<n;j++){
If(priority[j] > temp){
Temp=priority[j];
M=j;}
}
Swap(&priority[i], &priority[m]);
Swap(&burst[i], &burst[m]);
Swap(&index[i],&index[m]);
} Int t=0;
Printf(“Order of process Execution is\n”);
For(int i=0;i<n;i++) {
Printf(“P%d is executed from %d to %d\n”,index[i],t,t+burst[i]);
T+=burst[i];
} Printf(“\n”);
Printf(“Process Id\tBurst Time\tWait Time\n”);
Int wait_time=0;
Int total_wait_time = 0;
For(int i=0;i<n;i++){
Printf(“P%d\t\t%d\t\t%d\n”,index[i],burst[i],wait_time);
Total_wait_time += wait_time;
Wait_time += burst[i];
} Float avg_wait_time = (float) total_wait_time / n;
Printf(“Average waiting time is %f\n”, avg_wait_time);
Int total_Turn_Around = 0;
For(int i=0; I < n; i++){
Total_Turn_Around += burst[i];
}
Float avg_Turn_Around = (float) total_Turn_Around / n;
Printf(“Average TurnAround Time is %f”,avg_Turn_Around);
Return 0;
}
OUTPUT –
.

Experiment 4- Write a program to implement ROUND ROBIN CPU


scheduling.
#include<stdio.h>
Void main(){
Int I, NOP, sum=0,count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];
Float avg_wt, avg_tat;
Printf(“ Total number of process in the system: “);
Scanf(“%d”, &NOP);
Y = NOP;
For(i=0; i<NOP; i++) {
Printf(“\n Enter the Arrival and Burst time of the Process[%d]\n”, i+1);
Printf(“ Enter Arrival time: \t”);
Scanf(“%d”, &at[i]);
Printf(“ \nEnter Burst time: \t”);
Scanf(“%d”, &bt[i]);
Temp[i] = bt[i];
}
Printf(“Enter the Time Quantum for the process: \t”);
Scanf(“%d”, &quant);
Printf(“\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time “);
For(sum=0, I = 0; y!=0; ){
If(temp[i] <= quant && temp[i] > 0) {
Sum = sum + temp[i];
Temp[i] = 0;
Count=1;
}
Else if(temp[i] > 0) {
Temp[i] = temp[i] – quant;
Sum = sum + quant;
}
If(temp[i]==0 && count==1) {
y--;
printf(“\nProcess No[%d] \t\t %d\t\t\t\t %d\t\t\t %d”, i+1, bt[i], sum-at[i],
sum-at[i]-bt[i]);
wt = wt+sum-at[i]-bt[i];
tat = tat+sum-at[i];
count =0;
}
If(i==NOP-1) {
I=0;
}
Else if(at[i+1]<=sum) {
I++;
}Else{
I=0;
}
}
}
OUTPUT-
.
Experiment 5 - Write a c program to implement FIFO page
replacement algorithm.
#include < stdio.h >
Int main()
{
Int incomingStream[] = {4 , 1 , 2 , 4 , 5};
Int pageFaults = 0;
Int frames = 3;
Int m, n, s, pages;
Pages = sizeof(incomingStream)/sizeof(incomingStream[0]);
Printf(“ Incoming \ t Frame 1 \ t Frame 2 \ t Frame 3 “);
Int temp[ frames ];
For(m = 0; m < frames; m++)
{
Temp[m] = -1;
}
For(m = 0; m < pages; m++) {
S = 0;
For(n = 0; n < frames; n++)
{
If(incomingStream[m] == temp[n]) {
S++;
pageFaults--;
}
}
pageFaults++;
if((pageFaults <= frames) && (s == 0)) {
Temp[m] = incomingStream[m];
} Else if(s == 0)
{
Temp[(pageFaults – 1) % frames] = incomingStream[m];
}
Printf(“\n”);
Printf(“%d\t\t\t”,incomingStream[m]);
For(n = 0; n < frames; n++) {
If(temp[n] != -1)
Printf(“ %d\t\t\t”, temp[n]);
Else
Printf(“ - \t\t\t”);
}
}
Printf(“\nTotal Page Faults:\t%d\n”, pageFaults);
Return 0;
}
OUTPUT –
.
Experiment 6 – Write a c program to implement LRU page
replacement algorithm.
#include<stdio.h>
#include<limits.h>
Int checkHit(int incomingPage, int queue[], int occupied){
For(int I = 0; I < occupied; i++){
If(incomingPage == queue[i])
Return 1;
} Return 0;
}
Void printFrame(int queue[], int occupied){
For(int I = 0; I < occupied; i++)
Printf(“%d\t\t\t”,queue[i]);
}Int main(){
Int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3};
Int n = sizeof(incomingStream)/sizeof(incomingStream[0]);
Int frames = 3;
Int queue[n], distance[n];
Int occupied = 0;
Int pagefault = 0;
Printf(“Page\t Frame1 \t Frame2 \t Frame3\n”);
For(int I = 0;I < n; i++){
Printf(“%d: \t\t”,incomingStream[i]);
If(checkHit(incomingStream[i], queue, occupied)){
printFrame(queue, occupied);
}Else if(occupied < frames){
Queue[occupied] = incomingStream[i];
Pagefault++;
Occupied++;
printFrame(queue, occupied);
}Else{
Int max = INT_MIN;
Int index;
For (int j = 0; j < frames; j++){
Distance[j] = 0;
For(int k = I – 1; k >= 0; k--){
++distance[j];
If(queue[j] == incomingStream[k])
Break;
} If(distance[j] > max){
Max = distance[j];
Index = j;
}
}Queue[index] = incomingStream[i];
printFrame(queue, occupied);
pagefault++;
} Printf(“\n”);
} Printf("Page Fault: %d",pagefault);
return 0;
}
Experiment 7 – Write a c program to implement OPTIMAL page
replacement algorithm.
#include<stdio.h>
Int Main (){
Int n, pg[30], fr[10];
Int count[10], I, j, k, fault, f, flag, temp, current, c, dist, max, m, cnt,P, x;
Fault = Dist = K = 0;
Printf (“Enter the total no pages:\t”);
Scanf (“%d”, &n);
Printf (“Enter the sequence:”);
For (I = 0; I < n; i++)
Scanf (“%d”, &pg[i]);
Printf (“\nEnter frame size:”);
Scanf (“%d”, &f);
For (I = 0; I < f; i++){
Count[i] = 0; Fr[i] = -1;
} For (I = 0; I < n; i++){
Flag = 0;
Temp = pg[i];
For (j = 0; j < f; j++){
If (temp == fr[j]){
Flag = 1;
Break;
}
}If ((flag == 0) && (k < f)){
Fault++;
Fr[k] = temp;
K++;
} Else if ((flag == 0) && (k == f)){
Fault++;
For (cnt = 0; cnt < f; cnt++){
Current = fr[cnt];
For (c = I; c < n; c++){
If (current != pg[c])
Count[cnt]++;
Else{Break;}
} Max = 0;
For (m = 0; m < f; m++){
If (count[m] > max){
Max = count[m];
P = m;
}
}
Fr[p] = temp;
} Printf (“\npage %d frame\t”, pg[i]);
For (x = 0; x < f; x++){
Printf (“%d\t”, fr[x]);}
} Printf (“\nTotal number of faults=%d”, fault);
Return 0;
}
OUTPUT-

Common questions

Powered by AI

The FIFO page replacement algorithm is generally less efficient in reducing page faults compared to LRU and Optimal algorithms. FIFO replaces the oldest page in memory, which can lead to suboptimal decisions and more frequent page faults if the oldest page is frequently used. LRU improves on this by replacing the least recently used page, thereby better predicting future needs based on past usage, leading to fewer page faults. Optimal replacement theoretically offers the fewest page faults by replacing the page that will not be used for the longest time; however, it requires future knowledge. Thus, while FIFO is simple, its efficiency in minimizing page faults is lower than LRU and Optimal under most circumstances .

In Round Robin scheduling, each process receives a fixed time quantum in which to execute. If a process's burst time exceeds this quantum, the process is paused, and control passes to the next process in line. Processes with shorter burst times may complete in their initial quantum, minimizing their waiting time and turnaround time. The Round Robin approach handles variance in burst times by cycling through the ready queue, thus preventing longer processes from blocking others, which contrasts with FCFS, where such processes may bottleneck the system .

The FCFS algorithm calculates waiting time by accumulating burst times of preceding processes, leading to high waiting times if a long process precedes others . In contrast, the Round Robin algorithm uses time quanta to ensure that all processes receive equal CPU time early, reducing waiting times for shorter processes since the CPU cycles through each process avoiding long wait durations. While Round Robin might introduce more context switches, it tends to offer better average waiting times for shorter processes or when processes have varied burst times since it doesn't allow long processes to block the queue as in FCFS .

Choosing a specific CPU scheduling algorithm has significant implications for process execution time and overall system efficiency. FCFS can lead to long wait times under heavy loads or when processes are not evenly distributed in size, causing poor performance due to the convoy effect. SJF, while optimal in minimizing average waiting time under perfect conditions, is susceptible to starvation of longer processes. Round Robin provides fairness but increases context switches, possibly leading to inefficiencies if the time quantum is not optimally chosen. Priority-based scheduling offers flexibility but can cause low-priority process starvation. The choice of algorithm affects the balance between CPU utilization, throughput, turnaround time, and responsiveness, necessitating careful consideration of workload characteristics .

The primary challenge the Optimal Page Replacement algorithm faces is its requirement to foresee future requests in order to make the optimal decision about which page to replace. Unlike other strategies like LRU or FIFO, which use historical data to make decisions, the Optimal strategy needs access to or assumptions about future memory accesses to replace the page that will not be used for the longest time in the future. This requirement makes it impractical in real-world scenarios without predictive technology, as future page requests are typically unknown. However, it is used as a benchmark to measure the effectiveness of other algorithms .

The Shortest Job First (SJF) algorithm selects processes based on their burst times, always choosing the process with the shortest burst time available for execution next. Initially, processes and their burst times are input, and the algorithm then sorts these processes in ascending order of burst time. This sorting ensures that the next available process with the shortest execution requirement is selected, which minimizes waiting time across all processes, leading to a reduction in the average waiting time .

In the priority CPU scheduling algorithm, processes are executed based on their priority levels. The algorithm starts by taking input for burst time and priority for each process. It then sorts the processes in descending order of their priority values (i.e., higher priority values are selected first). The sorting is achieved by iterating over processes and swapping them based on their priority values. After sorting, the execution order follows the sorted priority, executing the process with the highest priority first and proceeding to the lower priorities .

In the FIFO page replacement algorithm, pages are replaced based on the order they were introduced into memory. When a new page needs to be loaded, and all frames are full, the processor replaces the oldest page—the one that has been in the frames the longest. This is managed by maintaining a queue of pages; when a page fault occurs and a new page is inserted, the page at the front of the queue (the oldest) is removed, and the new page is placed at the rear .

In the LRU page replacement algorithm, when a page fault occurs and the frames are fully occupied, the algorithm identifies the page in memory that has not been used for the longest period of time (the least recently used page). It does this by calculating the "distance" (i.e., time since last use) for each page in the current frames, finds the maximum distance, and replaces that page with the new page. If the page has been accessed more recently, this length of time (`distance[j]`) is smaller. By maintaining a list of distances and identifying the page with the largest value, the LRU algorithm identifies which page to swap out .

In FCFS CPU scheduling, the waiting time for each process is calculated by summing up the burst times of all preceding processes. Specifically, `wt[0]` is initially `0`, and for each subsequent process `i`, `wt[i]` is calculated as the burst time of the previous process plus the waiting time of the previous process (`wt[i] = bt[i-1] + wt[i-1]`). The turnaround time for each process is then calculated by adding its burst time to its waiting time (`tat[i] = bt[i] + wt[i]`).

You might also like