So, I have a random question when coding an image processing function, which is related to time complexity. Below is my original code snippet:
long start = System.currentTimeMillis(); for (int i = 0; i < newWidth; i++) { for (int j = 0; j < newHeight; j++) { double x = i * scaleX; double y = j * scaleY; double xdiff = x - (int) x; double ydiff = y - (int) y; int xf = (int) Math.floor(x); int xc = (int) Math.ceil(x); int yf = (int) Math.floor(y); int yc = (int) Math.ceil(y); double out = inputArray[xf][yf] * (1 - xdiff) * (1 - ydiff) + inputArray[xc][yf] * xdiff * (1 - ydiff) + inputArray[xf][yc] * (1 - xdiff) * ydiff + inputArray[xc][yc] * xdiff * ydiff; outputArray[i][j] = (int) out; } } long elapsed = System.currentTimeMillis() - start; System.out.println("Time used: " + elapsed);
And after exiting with this code, I was wondering if it would be faster not to create 4 temporary variables for the floor and ceiling values, but instead to calculate them directly in the indexing of the array. So I changed it as follows:
long start = System.currentTimeMillis(); for (int i = 0; i < newWidth; i++) { for (int j = 0; j < newHeight; j++) { double x = i * scaleX; double y = j * scaleY; double xdiff = x - (int) x; double ydiff = y - (int) y; double out = inputArray[(int) Math.floor(x)][(int) Math.floor(y)] * (1 - xdiff) * (1 - ydiff) + inputArray[(int) Math.ceil(x)][(int) Math.floor(y)] * xdiff * (1 - ydiff) + inputArray[(int) Math.floor(x)][(int) Math.ceil(y)] * (1 - xdiff) * ydiff + inputArray[(int) Math.ceil(x)][(int) Math.ceil(y)] * xdiff * ydiff; outputArray[i][j] = (int) out; } } long elapsed = System.currentTimeMillis() - start; System.out.println("Time used: " + elapsed);
I expected that later it would be faster (because you do not need to write to a temporary variable and then access it), but it turned out that the later version is at least 2.5 times slower than the previous code. The test case used is a 3x magnification of 1024x768 img.
old code: used time: 812 later code: used time: 2140
So what is the reason for the time difference?
source share