0

Good morning everybody, i'm trying to write a method that given a N number will create a spiral matrix with size of N*N, the method below works just fine but the execution time of the code is about 2s when it should be around few ms, i don't know what actually makes the code so slow, can you help me figure it out?, thanks.

I wrote another method that called this one (spirale) with different numbers in the following order and had the following results.

test1: n=10 execution time-> 2475ms
test2: n=5 execution time-> 7795ms
test3: n=1 execution time-> 7169ms
test4: n=0 execution time-> 7034ms
test5: n=6 execution time-> 7056ms



    public static int[][] spirale(int N){
    int i=0, j=0, giro = 0, numbers = 1;
    int mat[][] = new int[N][N];
    while(true){
        for(j=0+giro; j<N-giro; j++){
            if(numbers>N*N) return mat;
            mat[i][j] = numbers++;
        }
        j--;
        for(i=1+giro; i<N-giro ; i++){
            if(numbers>N*N) return mat;
            mat[i][j] = numbers++;
        }
        i--;
        for(j=N-2-giro; j>=0+giro; j--){
            if(numbers>N*N) return mat;
            mat[i][j] = numbers++;
        }
        j++;
        for(i=N-2-giro ; i>0+giro ; i--){
            if(numbers>N*N) return mat;
            mat[i][j] = numbers++;
        }
        i++;
        giro++;
    }

}
MWiesner
  • 8,868
  • 11
  • 36
  • 70
  • 1
    JVM startup and "warming" type is big enough to make these numbers "ordinary". If you need to measure _your code_ execution, you should use a method [like this](http://stackoverflow.com/questions/180158/how-do-i-time-a-methods-execution-in-java) – user3159253 Oct 24 '15 at 09:20

1 Answers1

0

In general this:

test4: n=0 execution time-> 7034ms

suggests that the problem not in the spirale method since it will return immidiately in first iteration here:

if(numbers>N*N) return mat;

I guess you should look in your code where you measure it (you have to measure it in code, not just the program execution time due to the process creation overhead)

Anyway, this is not important for the small N that you use, but you need to calculate N*N only once. I guess the compiler optimization will do the work for you though.

I mean:

int squareN = N*N;
 while(true){

        for(j=0+giro; j<N-giro; j++){
            if(numbers>squareN ) return mat;
            mat[i][j] = numbers++;
        }
        j--;
        for(i=1+giro; i<N-giro ; i++){
            if(numbers>squareN ) return mat;
            mat[i][j] = numbers++;
        }
        i--;
        for(j=N-2-giro; j>=0+giro; j--){
            if(numbers>squareN ) return mat;
            mat[i][j] = numbers++;
        }
        j++;
        for(i=N-2-giro ; i>0+giro ; i--){
            if(numbers>squareN ) return mat;
            mat[i][j] = numbers++;
        }
        i++;
        giro++;
    }
Roman Pustylnikov
  • 1,937
  • 1
  • 10
  • 18