How can I compare 2 methods in Java?

I have 2 methods in java (Factorial for example) and I have to check these 2 methods to find which one is faster. I have this code as Recursion and for the loop:

They are both in the same class data.

    public long FakultaetRekursiv( int n){
        if(n == 1){
        return 1;
        }
        else{
        return FakultaetRekursiv(n-1) * n;
        }
    }


    public long Fakultaet( int n){
        int x=1;
        for(int i=1; i<=n; i++){
            x= x*i;
        }
        return x;       
    }

      

I heard that currentTimeMillis () might help a little, but I don't know how. Thank.

+3


source to share


4 answers


Micro-benchmarking is difficult , use the right tools like Caliper . Here's an example that will work for you:

import com.google.caliper.SimpleBenchmark;

public class Benchmark extends SimpleBenchmark {

    @Param({"1", "10", "100"}) private int arg;

    public void timeFakultaet(int reps) {
        for (int i = 0; i < reps; ++i) {
            Fakultaet(arg);
        }
    }

    public void timeFakultaetRekursiv(int reps) {
        for (int i = 0; i < reps; ++i) {
            FakultaetRekursiv(arg);
        }
    }

}

      



The structure will run tour methods time*()

many times, moreover, it will enter different values arg

and highlight them separately.

+8


source


Always go to basics! Just use this to find the time taken by each of the functions



long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = endTime - startTime;

      

+3


source


long start = System.currentTimeMillis();

      

// your code is here

System.out.println(System.currentTimeMillis() - start + "ms");

      

+3


source


You can also do it manually:

The first method can be described with a recurrent relationship F(x) = F(x-1) * x

that generates a template ...

F(x) = F(x-1) * x
= F(x-2)*x*(x-1)
= F(x-3)*x*(x-1)*(x-2)
. . .
= k*n

      

which is O (n).

Obviously, the second method can be described as O (n) as well, which means that they are in the same upper bound. But this can be used as a quick check before implementing synchronization solutions.

-1


source







All Articles