-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprofileMe.go
128 lines (113 loc) · 1.98 KB
/
profileMe.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"fmt"
"math"
"os"
"runtime"
"runtime/pprof"
"time"
)
func fibo1(n int) int64 {
if n == 0 || n == 1 {
return int64(n)
}
time.Sleep(time.Millisecond)
return int64(fibo2(n-1)) + int64(fibo2(n-2))
}
func fibo2(n int) int {
fn := make(map[int]int)
for i := 0; i <= n; i++ {
var f int
if i <= 2 {
f = 1
} else {
f = fn[i-1] + fn[i-2]
}
fn[i] = f
}
time.Sleep(50 * time.Millisecond)
return fn[n]
}
func N1(n int) bool {
k := math.Floor(float64(n/2 + 1))
for i := 2; i < int(k); i++ {
if (n % i) == 0 {
return false
}
}
return true
}
func N2(n int) bool {
for i := 2; i < n; i++ {
if (n % i) == 0 {
return false
}
}
return true
}
/*
start the profiling:
go run profileMe.go
check out the result:
go tool pprof /tmp/cpuProfile.out # this would drop us in _pprof REPL_
> top
> top10 --cum
> list main.N1
*/
func main() {
cpuFile, err := os.Create("/tmp/cpuProfile.out")
if err != nil {
fmt.Println(err)
return
}
// The `pprof.StartCPUProfile()` call begins the CPU profiling of the program,
// and the call to `pprof.StopCPUProfile()` stops it.
pprof.StartCPUProfile(cpuFile)
defer pprof.StopCPUProfile()
total := 0
for i := 2; i < 100000; i++ {
n := N1(i)
if n {
total = total + 1
}
}
fmt.Println("Total primes:", total)
total = 0
for i := 2; i < 100000; i++ {
n := N2(i)
if n {
total = total + 1
}
}
fmt.Println("Total primes:", total)
for i := 1; i < 90; i++ {
n := fibo1(i)
fmt.Print(n, " ")
}
fmt.Println()
for i := 1; i < 90; i++ {
n := fibo2(i)
fmt.Print(n, " ")
}
fmt.Println()
runtime.GC()
// Memory profiling!
memory, err := os.Create("/tmp/memoryProfile.out")
if err != nil {
fmt.Println(err)
return
}
defer memory.Close()
for i := 0; i < 10; i++ {
s := make([]byte, 50000000)
if s == nil {
fmt.Println("Operation failed!")
}
time.Sleep(50 * time.Millisecond)
}
err = pprof.WriteHeapProfile(memory)
if err != nil {
fmt.Println(err)
return
}
}