Skip to content

Instantly share code, notes, and snippets.

@georgepowell
Created February 27, 2017 14:05
Show Gist options
  • Save georgepowell/0bb67c768e661bda6bdbc8ab96de1a04 to your computer and use it in GitHub Desktop.
Save georgepowell/0bb67c768e661bda6bdbc8ab96de1a04 to your computer and use it in GitHub Desktop.
Timing the 2^n approach
import java.util.*;
public class Main {
public static void main(String[] args) {
for (int n = 0; n < 1000; n++) {
long startTime = System.nanoTime();
fib(n);
long endTime = System.nanoTime();
double duration = (endTime - startTime) / 1000000000.0;
System.out.println(n + ": " + duration + "s");
}
}
static int fib(int n) {
return n < 2 ? 1 : fib(n - 1) + fib(n - 2);
}
}
@georgepowell
Copy link
Author

0: 1.459E-6s
1: 3.65E-7s
2: 7.29E-7s
3: 3.65E-7s
4: 7.29E-7s
5: 1.094E-6s
6: 1.094E-6s
7: 1.823E-6s
8: 2.553E-6s
9: 2.917E-6s
10: 5.47E-6s
11: 7.657E-6s
12: 1.2397E-5s
13: 2.9172E-5s
14: 3.3182E-5s
15: 4.9956E-5s
16: 3.063E-5s
17: 1.0574E-5s
18: 1.4585E-5s
19: 2.8078E-5s
20: 4.1934E-5s
21: 6.4542E-5s
22: 1.02829E-4s
23: 1.76487E-4s
24: 2.96818E-4s
25: 4.6419E-4s
26: 7.36213E-4s
27: 0.001196027s
28: 0.001923489s
29: 0.002393878s
30: 0.004354926s
31: 0.007259667s
32: 0.011191973s
33: 0.017898478s
34: 0.030590225s
35: 0.05437695s
36: 0.084561692s
37: 0.134759474s
38: 0.211308513s
39: 0.337743563s
40: 0.547100144s
41: 0.794664332s
42: 1.286641832s
43: 2.095200503s
44: 3.379384644s
45: 5.368682022s
46: 9.034018959s
47: 14.403852886s
48: 22.809875759s
49: 36.778968295s
50: 63.223903629s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment