-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlevel02.go
79 lines (69 loc) · 1.63 KB
/
level02.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"fmt"
"runtime"
"time"
)
func level02() {
fmt.Print("\n* Fibonacci Using Recursion")
timeTaken(fibonacciRecursive, int64(40))
fmt.Print("\n* Fibonacci Using Iteration")
timeTaken(fibonacciIterative, int64(40))
var n int64 = 2000000000
fmt.Println("\n* 4 times in a row: Fibonacci Using Iteration")
fourTimes := func(n int64) int64 {
for i := 0; i < 4; i++ {
timeTaken(fibonacciIterative, n)
}
return 0
}
timeTaken(fourTimes, n)
fmt.Println("\n* 4 times in a row: Fibonacci Using Iteration And Concurrency")
start := time.Now()
c := make(chan int64)
for i := 0; i < 4; i++ {
go fibonacciIterativeConcurrent(n, c)
fmt.Println(": ", <-c)
}
stop := time.Now()
fmt.Println(": ", stop.Sub(start))
fmt.Println("\n* 4 times in a row: Fibonacci Using Iteration And Concurrency With Multiple CPUs: ",
runtime.NumCPU())
runtime.GOMAXPROCS(runtime.NumCPU()) //number of CPUs
start = time.Now()
c = make(chan int64)
for i := 0; i < 4; i++ {
go fibonacciIterativeConcurrent(n, c)
fmt.Println(": ", <-c)
}
stop = time.Now()
fmt.Println(": ", stop.Sub(start))
}
func timeTaken(f func(int64) int64, i int64) {
start := time.Now()
fmt.Print(": ", f(i))
stop := time.Now()
fmt.Println(": ", stop.Sub(start))
}
func fibonacciRecursive(n int64) int64 {
switch n {
case 0:
return 0
case 1:
fallthrough
case 2:
return 1
default:
return fibonacciRecursive(n-1) + fibonacciRecursive(n-2)
}
}
func fibonacciIterative(n int64) int64 {
var x, y int64 = 0, 1
for i := n; i > 1; i-- {
x, y = y, x+y
}
return y
}
func fibonacciIterativeConcurrent(n int64, c chan int64) {
c <- fibonacciIterative(n)
}