Sunday, 31 March 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.
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
No comments:
Post a Comment