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.
source to share
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.
source to share
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.
source to share