I'm seeing some strange behaviour in Java:
Commenting a println
makes the function execute slower.
Uncommenting the println
makes the function execute faster.
I would expect this to be reversed, as println
should cost time.
The trigger is the System.out.println("");
in the sequentialProcessData
function.
With the line commented I get 2.5 secs.
With the line uncommented I get 1.9 secs.
The behaviour is independent of using nanotime()
or currentTimeMillis()
to measure time.
Also, I could not reproduce the behaviour when triggering the println
with a flag.
Tested with Eclipse, jdk1.7.0_51 (JavaSE), Windows 7 (8 cores in case that matters).
Thanks
EDIT
This behaviour only occurs for me when I compile the code in Eclipse. (running in Eclipse and in the shell both have this strange behaviour)
If I compile in the shell (javac Main.java), then the behaviour is normal, i.e. the println version is slower (by about 1 secs).
So something strange with the Eclipse compiler?
Code:
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Generate Data Matrix with random numbers
int ROWS = 10000;
int COLS = 40;
double[][] data = generateData(ROWS,COLS);
//Variables
long start_main;
long end_main;
// Time consuming function
start_main = System.nanoTime();
sequencialProcessData(data);
end_main = System.nanoTime();
System.out.println("main duration: " + (end_main - start_main)*Math.pow(10, -9) + " secs");
}
static double[][] sequencialProcessData(double[][] data) {
double[][] result = new double[data.length][data[0].length];
for(int col = 0; col < data.length; ++col) {
for(int row = 0; row < data[col].length; ++row) {
for(int i = 0; i <= row; ++i) {
result[col][row] += data[col][i];
}
}
}
// TRIGGER : COMMENT and UNCOMMENT THIS to see a difference in performance
// System.out.println("");
return result;
}
static double[][] generateData(int ROWS,int COLS) {
double[][] data = new double[COLS][ROWS];
Random random = new Random();
for(int col = 0; col < COLS; ++col) {
for(int row = 0; row < ROWS; ++row) {
data[col][row] = random.nextDouble();
}
}
return data;
}
}