How can I compare 2 methods in Java?

I have two methods in Java (such as factorial calculation), and I have to test these two methods to find out which is faster I treat this code as recursion and loop:

They are all in the same kind of 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, but I don't know what to do thank you.

Solution

Micro benchmarking is hard, use the correct tool, such as caliper This is an example 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 the patrol time * () method many times, and it will inject different Arg values and mark them separately

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>