雑なメモ書き

気楽にいきます

Goのruntime/traceをつかってみる

実際に動作させる

  • ちょうどgoroutineを使う処理を直近のblogで試してた
  • これへ解析を追加する
package main

import (
    "fmt"
    "log"
    _ "net/http/pprof"
    "os"
    "runtime/trace"
    "time"
)

func main() {

    f, err := os.Create("trace.out")
    if err != nil {
        log.Fatal(err)
    }

    defer f.Close()

    trace.Start(f)
    defer trace.Stop()

    ch := generator("Hi!")
    timeout := time.After(5 * time.Second)
    for i := 0; i < 10; i++ {
        select {
        case s := <-ch:
            fmt.Println(s)
        case <-timeout: // time.After returns a channel that waits N time to send a message
            fmt.Println("5s Timeout!")
            return
        }
    }
}

func generator(msg string) <-chan string { // returns receive-only channel
    ch := make(chan string)
    go func() { // anonymous goroutine
        for i := 0; ; i++ {
            ch <- fmt.Sprintf("%s %d", msg, i)
            time.Sleep(time.Second)
        }
    }()
    return ch
}

解析コマンド

go tool trace trace.out

結果

ブラウザで見られるがこんな感じ。

f:id:hiroyukim:20190127140256p:plain

f:id:hiroyukim:20190127140315p:plain