logo头像
Snippet 博客主题

golang cpu leak time.Tick()

Go time.Tick CPU Leak issue

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
package main

import (
"log"
"net/http"
"time"

_ "net/http/pprof"
)

func main() {
http.HandleFunc("/test", handler)
log.Fatal(http.ListenAndServe(":9876", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
doSomething(10000)
}

func doSomething(times int) {
for i := 0; i < times; i++ {
for j := 0; j < times; j++ {
timeTick_loop()
}
}
}

func timeTick_loop() {
throttle := time.Tick(300 * time.Millisecond)
for i := 0; i < 100; i++ {
// fmt.Println("do some db save")
<-throttle
}
}

func timeTick_lifetime() {
for range time.Tick(300 * time.Millisecond) {
// fmt.Println("test")
return
}
}

func timeNewTicker() {
ticker := time.NewTicker(300 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// fmt.Println("do some db save")
return
}
}
}

Local Case by Pprof: create a simple web app:

brew install wrk
wrk -t8 -c400 -d3m http://localhost:9876/test
http://localhost:9876/debug/pprof/profile

Pprof CPU leak

Activity_Monitor CPU leak

More Reading:

https://www.gitdig.com/cpu-leak/
https://blogtitle.github.io/go-advanced-concurrency-patterns-part-2-timers/#time.Ticker