Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 638
altank52 Avatar asked Dec 11 '22 18:12

altank52


1 Answers

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.

like image 195
Tomasz Nurkiewicz Avatar answered Dec 15 '22 00:12

Tomasz Nurkiewicz