I have written a program for Round Robin Scheduling for CPU processes. The program was working fine before, but all of a sudden, the program stops working after several lines of code. I have tried to restart the Dev C++ app but the issue still persists. Is something wrong with my code?
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int i,n,time,remaining,temp,quantum_time;
int wt=0,atat=0; //wt = Waiting Time, atat = Average Turn Around Time
cout<<"Enter the number of processes to be scheduled"<<endl;
cin>>n;
remaining=n;
vector<int>at(n);
vector<int>bt(n);
vector<int>rt(n); //Dynamic array declaration using 'vector' library
cout<<"Enter the Arrival Time and Burst Time for all the processes"<<endl;
for(i=0;i<n;i++)
{
cin>>at[i];
cin>>bt[i];
rt[i]=bt[i];
}
cout<<"Enter the Quantum Time:"<<endl;
cin>>quantum_time;
cout<<"\n\nProcess\t\t: Arrival Time\t: Burst Time\t: Turnaround Time : Waiting Time\n\n";
for(time=0,i=0;remaining!=0;)
{
if(rt[i]<=quantum_time&&rt[i]>0)
{
time+=rt[i];
rt[i]=0;
temp=1;
}
else if(rt[i]>0)
{
rt[i]-=quantum_time;
time+=quantum_time;
}
if(rt[i]==0&&temp==1)
{
remaining--;
printf("Process{%d}\t:\t%d\t:\t%d\t:\t %d\t :\t %d\n",i+1,at[i],bt[i],time-at[i],time-at[i]-bt[i]);
cout<<endl;
wt += time-at[i]-bt[i];
atat += time-at[i];
temp=0;
}
if(i==n-1)
i=0;
else if(at[i+1]<=time)
i++;
else
i=0;
}
cout<<"Average Waiting Time: "<<wt*1.0/n<<endl;
cout<<"Average TurnAround Time: "<<atat*1.0/n<<endl;
return 0;
}
When I try to schedule 2 or more processes, the program gets stuck after displaying process 1
You have the wrong logic in the for iteration loop. The point is that your program iterates through this loop endlessly. After the first two loops, your entered data does not satisfy any condition, and i always resets to zero, so the program is constantly checking for the same unsuitable data.
The changes I've made will fix the program's freeze. But I'm not sure that I was able to keep your logic correct. So, I changed the 'for' loop like this: for (time = 0, i = 0; remaining > 0;), now we will be sure that the program will be able to complete.
Also, at the very end of the 'for' loop I put a remaining--; (approximately, line 55). I know that one of the conditions decreases this variable, but your program does not go into this condition every time.
Related
I have recently started learning c++ and I have a question regarding the last section I reached, the while loop one.
In this code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
return 0;
}
will the while command continue checking if i <=5 after the value goes over 5 or will it stop?
If I was making a program and changed the value of i down the line to one that meets the condition of the loop would it start again or would I have to rewrite the loop code again?
Thanks in advance for the answers!
edit: Thanks for your answers and comments. I tried putting into code what I was thinking and I noticed that changing the value of i after the loop didn't make it start again(meaning that it had already stopped checking after i surpassed 5).
I realize it was a stupid question that I could have simply solved by trying to put it into code, but I still asked for answers just to be sure. Thanks again!
If you changed i to 0 after the loop has ended like this:
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
i=0;
return 0;
}
The loop wouldn't start again because it would just set i to 0 and then go to return 0. Once the loop is executed it won't be run again.
Note that C++ executes the code sequentially, this means that its goes through every line, executes it, then goes to the next one. This is confusing for loops because you see previous code being executed again; therefore, to solve this dilemma, think of the loop segment as a block, once this block executes, the normal sequential execution continues.
For Future reference: C++ has a beautiful feature called Multi-threading, where you can allow several code to execute in a parallel fashion. You will meet this feature sometime in the future.
especially,the larger the number of cycles is,the more obvious the difference becomes.
test in g++ without optimization
int main()
{
int a[]={0,0};
int b[]={0,0};
//first loop
for(unsigned int i=0;i<0x00FFFFFF;i++)
{
a[0]++;a[1]++;
}
//second loop
for(unsigned int i=0;i<0x00FFFFFF;i++)
{
b[0]++;b[0]++; //yes it's b[0] not b[1]
}
return 0;
}
Somebody may not believe me,me either.But in this code the first loop is at least two times faster than the second one.
I suspect it's a pipelining issue. In the first loop you're writing to two different memory locations, so the second addition doesn't need to wait for the first one to finish, and the CPU can do both at once.
In the second loop, you're incrementing the same variable both times, so the second one has to wait for the first one to finish. This slows down the pipeline.
I am writing a program that does calculations in multiple threads and return the result using c++ future, here's a simplified version of my code
int main()
{
int length = 64;
vector<std::future<float>> threads(length);
vector<float> results(length);
int blockLength = 8;
int blockCount = length/blockLength;
for(int j=0;j<blockCount;j++)
{
for(int i=0;i<blockLength;i++)
{
threads[i + j * blockLength] = std::async(func1,i*j);
}
for(int i=0;i<blockLength;i++)
{
results[i + j * blockLength] = threads[i].get();
}
}
the definition of func1 is simplified as follows:
float func1(int input)
{
//calculations...
return result;
}
I would like that the program above does 64 times of calculations, in 8 threads at a time, so that the processor and memory usage would be better at the same time.
The program is conceived that it will post blockLength number of threads at a time, and wait till the calculation results are obtained, and proceed to the next loop.
the program will post blockLength number of threads for blockCount times, for example, 8 threads for 8 times.
but the program is not working, there is always a EXC_BAD_ACCESS exception when the first loop of blockLength threads finishes, besides, the calculation time of each thread is not guaranteed, any thread can run for a long time or finish quickly.
Here is a screenshot:
as is shown above, the CPU usage drops as some of the threads finish, but an exception is thrown as soon as the second loop starts.
Would you please point out what is wrong with my usage of future?
How can we correct it?
Thank you very much!
I wrote the following code, that must do search of all possible combinations of two digits in a string whose length is specified:
#include <iostream>
#include <Windows.h>
int main ()
{
using namespace std;
cout<<"Enter length of array"<<endl;
int size;
cin>>size;
int * ps=new int [size];
for (int i=0; i<size; i++)
ps[i]=3;
int k=4;
SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
while (k>=0)
{
for (int bi=0; bi<size; bi++)
std::cout<<ps[bi];
std::cout<<std::endl;
int i=size-1;
if (ps[i]==3)
{
ps[i]=4;
continue;
}
if (ps[i]==4)
{
while (ps[i]==4)
{
ps[i]=3;
--i;
}
ps[i]=4;
if (i<k)
k--;
}
}
}
When programm was executing on Windows 7, I saw that load of CPU is only 10-15%, in order to make my code worked faster, i decided to change priority of my programm to High. But when i did it there was no increase in work and load of CPU stayed the same. Why CPU load doesn't change? Incorrect statement SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);? Or this code cannot work faster?
If your CPU is not working at it's full capacity it means that your application is not capable of using it because of causes like I/O, sleeps, memory or other device throughtput capabilties.
Most probably, however, it means that your CPU has 2+ cores and your application is single-threaded. In this case you have to go through the process of paralellizing your application, which is often neither simple nor fast.
In case of the code you posted, the most time consuming operation is actually (most probably) printing the results. Remove the cout code and see for yourself how fast the code will work.
Increasing the priority of your programm won't help much.
What you need to do is to remove the cout from your calculations. Store your computations and output them afterwards.
As others have noted it might also be that you use a multi-core machine. Anyway removing any output from your computation loop is always a first step to use 100% of your machines computation power for that and not waste cycles on output.
std::vector<int> results;
results.reserve(1000); // this should ideally match the number of results you expect
while (k>=0)
{
for (int bi=0; bi<size; bi++){
results.push_back(ps[bi]);
}
int i=size-1;
if (ps[i]==3)
{
ps[i]=4;
continue;
}
if (ps[i]==4)
{
while (ps[i]==4)
{
ps[i]=3;
--i;
}
ps[i]=4;
if (i<k)
k--;
}
}
// now here yuo can output your data
for(auto&& res : results){
cout << res << "\n"; // \n to not force flush
}
cout << endl; // now force flush
What's probably happening is you're on a multi-core/multi-thread machine and you're running on only one thread, the rest of the CPU power is just sitting idle. So you'll want to multi-thread your code. Look at boost thread.
here i have written a program on (3n+1) problem.it's also a problem from UVa. I believe it's a known problem.but when i am going to submit it in that online judge community it is sending me a Time Exceeding Error. the time limit is 3 sec. I have done what my little knowledge can do. If anyone can help me with some more advice I would be glad. my code is:
#include <iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main()
{
int loop=1;
unsigned short *cyclelength;
while(loop=1){
unsigned int x,y,i,j,num,count=0,p,k,c,max;
for(;;){
cout<<"enter two integers. they must not be equal and must be between 1 and 1000000\n";
while(!(cin>>i>>j)){
cout<<"please enter a number\n";
cin.clear();
cin.ignore(1000,'\n');
}
if(i>=1 && i<1000000 && j>=1 && j<1000000 && i!=j){
break;
}
else{
printf("try the whole process again\n");
}
}
if(i>j){
x=i;
y=j;
}
else{
x=j;
y=i;
}/*making x always greater than y*/
cyclelength=(unsigned short *)malloc(1000000 *sizeof(unsigned short));
if (NULL==cyclelength){
printf("process aborted");
return 0;
}
else{
/*solution part for the range of number. and solution for each number put into cyclelength.*/
num=y;
while(num<=x){
p=1;
k=num;
while(k!=1){
if(k%2==0)
k=k/2;
else
k=3*k+1;
p+=1;
}
cyclelength[count]=p;
num+=1;
count+=1;
}
c=0;
max=cyclelength[c];
for(c=0;c<x-y-1;c+=1){
if(max<cyclelength[c+1]){
max=cyclelength[c+1];
}
}
free(cyclelength);
cyclelength = NULL;
cout<<i<<" "<<j<<" "<<max<<'\n';
}
}
}
The problem is that you are not allowing your program to end when online judging engine has finished providing inputs. You need to detect that the judging engine has finished providing inputs and then exit the program.
There is a sample code (in C) on their website here Spoiler Alert: This is actually a solution to 3n+1 problem that kind of explains this. Notice the following condition in Main.
while (scanf("%d %d\n",&m,&n)==2){//perform logic}
This will keep the program running only while there are inputs to be processed.
If your program is running successfully on your pc, but is giving time limit exceeding problem while you are submitting in any online judge community. It is sure that your algorithm is not most efficient. Online line judge communities put the time limit for any program such that an upper average programmer only can design their algorithm. Try to make your programming algorithm best after that try to take it to any online judge community. If you are using any test like >= or <= in your program it takes too much time to run your program.