Sunday, March 31, 2019
java - 2 "for" loops twice faster than 1 loop
Answer
I noticed that the below code
boolean hasFoundSurplusChangedSign = false;
int h = 1;
for(int k=0; k if (k==0){
mVCBArray[k]=mVBArray[k];
}else{
mVCBArray[k]=mVCBArray[k-1]+mVBArray[k];
}
mMVTArray[k]= Math.min(mVCBArray[k],mVCAArray[k]);
mSArray[k]= mVCBArray[k]-mVCAArray[k];
if (!hasFoundSurplusChangedSign && k>0){
if (Integer.signum(mSArray[k]) * Integer.signum(mSArray[k-1]) > 0){
h = k+1;
}else{
hasFoundSurplusChangedSign = true;
}
}
}
runs faster than this one :
boolean hasFoundSurplusChangedSign = false;
int h = 1;
for(int k=0; k if (k==0){
mVCBArray[k]=mVBArray[k];
}else{
mVCBArray[k]=mVCBArray[k-1]+mVBArray[k];
}
mMVTArray[k]= Math.min(mVCBArray[k],mVCAArray[k]);
mSArray[k]= mVCBArray[k]-mVCAArray[k];
}
for(int k=0; k if (!hasFoundSurplusChangedSign && k>0){
if (Integer.signum(mSArray[k]) * Integer.signum(mSArray[k-1]) > 0){
h = k+1;
}else{
hasFoundSurplusChangedSign = true;
}
}
}
all the Arrays are int arrays. The size of each array is constant and equal to 1000.
the for loops iterate roughly 100 times (ie size = 100 roughly).
So, the first code runs in average in 6 microsecond while the second code runs in 3.5 microsecond.
It seems that splitting the loop into two smaller loops improve the performance of my code here.
Why?
Is it the compiler that compile differently the two versions of my code?
I read somewhere that it could be because the processor cannot put the whole loop code in its cache and so needs to swap between different cache zone, while in the second case, it could, so it goes faster. I am not sure to understand this argument. Does that sounds possible to you?
Any other ideas?
Thanks for your much needed help on this one.
plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV
In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...
-
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programm...
-
I need to do the following: My current address looks like: https://www.domain.com I want to redirect with htaccess: www.domain.com TO https:...
-
using namespace std; So far in my computer science courses, this is all we have been told to do. Not only that, but it's all tha...
No comments:
Post a Comment