I have a piece of code that needs to do many computations based on double values, which takes too much time. Can I speed this up by dropping some decimals? if I use a formatter to parse the double, won’t that do the calculus first and then shed the extra decimals, so nothing would be gained? what’s the best way of doing this?
Just something to get an idea:
double avgRatingForPreferredItem = (double) tempAverageRating.get(matrix.get(0).getItemID1())/matrix.size();
double avgRatingForRandomItem = (double) tempAverageRating.get(matrix.get(0).getItemID2())/matrix.size();
double numarator = 0;
for (MatrixColumn matrixCol : matrix) {
numarator += ( matrixCol.getRatingForItemID1() - avgRatingForPreferredItem ) * (matrixCol.getRatingForItemID2() - avgRatingForRandomItem);
}
double numitor = 0;
double numitorStanga = 0;
double numitorDreapta = 0;
for (MatrixColumn matrixCol : matrix) {
numitorStanga += (matrixCol.getRatingForItemID1() - avgRatingForPreferredItem) * (matrixCol.getRatingForItemID1() - avgRatingForPreferredItem);
numitorDreapta += (matrixCol.getRatingForItemID2() - avgRatingForRandomItem) * (matrixCol.getRatingForItemID2() - avgRatingForRandomItem);
}
numitor = Math.sqrt( numitorStanga * numitorDreapta );
double corelare = numarator/numitor;
I don’t believe the actual values involved can make any difference.
It’s worth at least trying to reduce the computations here:
It depends on how smart the JIT compiler is – and I’m assuming
getRatingforItemID1andgetRatingforItemID2are just pass-through properties – but your code at least looks like it’s doing redundant subtractions. So:You could try changing everything to
floatinstead ofdouble– on some architectures that may make things faster; on others it may well not.Are you absolutely sure that it’s the code you’ve shown which has the problem, though? It’s only an O(N) algorithm – how long is it taking, and how large is the matrix?