Skip to content

Instantly share code, notes, and snippets.

@shmurakami
Created March 3, 2023 06:49
Show Gist options
  • Save shmurakami/bd5e7f1a780b1c1bae54ade98a6b48b6 to your computer and use it in GitHub Desktop.
Save shmurakami/bd5e7f1a780b1c1bae54ade98a6b48b6 to your computer and use it in GitHub Desktop.
golang run gc sample
package main
import (
"fmt"
"net/http"
"runtime"
"strconv"
"strings"
"time"
)
type S struct {
id int
num int
value string
}
var m map[string]*S
func init() {
m = make(map[string]*S)
}
func main() {
go server()
fin := make(chan bool)
go loop(fin)
go mem(fin)
<-fin
<-fin
fmt.Println("done")
}
func loop(c chan bool) {
snooze := time.NewTicker(1 * time.Second)
mem := time.Tick(9 * time.Second)
after := time.After(5 * time.Minute)
//sec := 0
go func() {
for {
select {
case <-snooze.C:
//fmt.Print(sec, " ")
//sec += 1
case <-mem:
go func() {
fmt.Println("start putting to heap")
for i := 0; i < 10000000; i++ {
key := fmt.Sprintf("key_%d", i)
m[key] = &S{id: i, num: i, value: "foo"}
}
fmt.Println("done to put")
m = make(map[string]*S)
fmt.Println("run GC")
runtime.GC()
}()
}
}
}()
<-after
snooze.Stop()
c <- true
}
func numberFormat(v uint64) string {
s := strconv.FormatUint(v, 10)
leftLen := len(s) % 3
rightBlock := len(s) / 3
var str []string
if leftLen > 0 {
left := s[0:leftLen]
str = append(str, left)
}
for i := 0; i < rightBlock; i++ {
base := i*3 + leftLen
b := s[base : base+3]
str = append(str, b)
}
return strings.Join(str, ",")
}
func mem(c chan bool) {
snooze := time.NewTicker(1 * time.Second)
fin := time.After(5 * time.Minute)
go func() {
for {
select {
case <-snooze.C:
var mem runtime.MemStats
runtime.ReadMemStats(&mem)
fmt.Printf("Memory Stats:: Heap Allocated: %s, Heap Idle: %s, Heap In Use: %s, Heap Objects: %s\n",
numberFormat(mem.HeapAlloc), numberFormat(mem.HeapIdle), numberFormat(mem.HeapInuse), numberFormat(mem.HeapObjects))
}
}
}()
<-fin
snooze.Stop()
c <- true
}
func server() {
fmt.Println("start server:: localhost:18080")
http.HandleFunc("/", handler)
err := http.ListenAndServe(":18080", nil)
if err != nil {
panic("failed to start server")
}
}
func handler(w http.ResponseWriter, req *http.Request) {
_, _ = fmt.Fprintf(w, "hello")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment