altank52
altank52

Reputation: 31

How can i compare 2 method in Java?

I have 2 methods in java (for example Factorial calculation) and i have to test these 2 methods to find which one is faster. I have that code as Recursion and as for loop:

They 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 currentTimeMillis() could help a little but i dont know how to do exactly. Thanks.

Upvotes: 3

Views: 1957

Answers (4)

sdasdadas
sdasdadas

Reputation: 25096

You can also do it by hand:

The first method can be described with a recurrence relation of F(x) = F(x-1) * x which generates the pattern...

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 by O(n) as well, which means they are in the same upper bound. But this can be used as a quick check before implementing timing solutions.

Upvotes: -1

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

Micro-benchmarking is hard, use the right tools, for example Caliper. Here is 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 framework will run tour time*() methods a lot of times, moreover it will inject different arg values and bechmark them separately.

Upvotes: 8

isvforall
isvforall

Reputation: 8926

long start = System.currentTimeMillis();

// your code here

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

Upvotes: 3

Aakash Anuj
Aakash Anuj

Reputation: 3871

Always go by the 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;

Upvotes: 3

Related Questions