Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- //#define INT_MAX 2147483647
- typedef struct job{
- int id;
- int at;
- int bt;
- int st;
- int ct;
- int wt;
- int tat;
- int pr;
- } job;
- void sortJobsAT(job jobs[], int n){
- int i, j;
- job t;
- for(i = 0; i < n-1; i++){
- for(j = i+1; j < n; j++){
- if (jobs[i].at > jobs[j].at){
- t = jobs[i];
- jobs[i] = jobs[j];
- jobs[j] = t;
- }
- }
- }
- }
- void calc(job jobs[], int n){
- int *rt = (int*)malloc(sizeof(int)*n);
- int i, j;
- for(i = 0; i < n; i++){
- rt[i] = jobs[i].bt;
- }
- int complete = 0, t = 0, minm = INT_MAX;
- int mostImportant = 0, finish_time;
- bool check = false;
- while (complete != n){
- for(j = 0; j < n; j++){
- if ((jobs[j].at > t) || ((rt[j] == 0))){
- continue;
- }
- if (jobs[j].pr < minm){
- minm = jobs[j].pr;
- mostImportant = j;
- check = true;
- }
- }
- if (check == false){
- t++;
- continue; //no process in ready queue
- }
- //printf("\nt=%d, Process %d", t, mostImportant);
- if (rt[mostImportant] == jobs[mostImportant].bt){
- jobs[mostImportant].st = t;
- }
- rt[mostImportant]--;
- if (rt[mostImportant] == 0){
- complete++;
- check = false;
- minm = INT_MAX;
- jobs[mostImportant].ct = t+1;
- jobs[mostImportant].wt = jobs[mostImportant].ct - jobs[mostImportant].bt - jobs[mostImportant].at;
- jobs[mostImportant].wt = (jobs[mostImportant].wt < 0 ) ? 0 : jobs[mostImportant].wt;
- jobs[mostImportant].tat = jobs[mostImportant].ct - jobs[mostImportant].at;
- }
- t++;
- }
- }
- void solve(){
- int k;
- printf("\n\tPriority Scheduling Algorithm\n");
- printf("\n1. Same Arrival time (0)");
- printf("\n2. Different Arrival Times\n>>");
- scanf("%d", &k);
- if (!(k == 1) && !(k == 2)){
- printf("\nINVALID");
- exit(0);
- }
- int n;
- printf("Enter number of processes: ");
- scanf("%d", &n);
- job *jobs;
- jobs = (job*)malloc(sizeof(job)*n);
- int i;
- for(i=0; i < n; i++){
- jobs[i].id = i;
- if (k != 1){
- printf("Enter Arrival Time of Process %d: ", i);
- scanf("%d", &jobs[i].at);
- }
- else{
- jobs[i].at = 0;
- }
- printf("Enter Burst Time of Process %d: ", i);
- scanf("%d", &jobs[i].bt);
- printf("Enter Priority of Process %d: ", i);
- scanf("%d", &jobs[i].pr);
- printf("\n");
- }
- sortJobsAT(jobs, n);
- calc(jobs, n);
- printf("\nID\tAT\tBT\tPR\tST\tCT\tWT\tTAT");
- for (i = 0; i < n; i++){
- printf("\n%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d", jobs[i].id, jobs[i].at, jobs[i].bt, jobs[i].pr, jobs[i].st, jobs[i].ct, jobs[i].wt, jobs[i].tat);
- }
- float avgWT = 0;
- float avgTAT = 0;
- for(i = 0; i < n; i++){
- avgWT += jobs[i].wt;
- avgTAT += jobs[i].tat;
- }
- avgWT /= n;
- avgTAT /= n;
- printf("\nAverage Waiting Time = %f\nAverage Turnaround Time = %f", avgWT, avgTAT);
- }
- int main(){
- solve();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement