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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With