LoginSignup
0
0

More than 5 years have passed since last update.

Timeパッケージを使って簡易ベンチマークを取ってみる

Last updated at Posted at 2019-03-31

個人的にメモ。
原始的だが time.Time パッケージを使って、終了時間から開始時間をSubする。

func BenchFuncSeconds(f func() error) error {
    st := time.Now()
    err := f()
    if err != nil {
        return err
    }
    ed := time.Now()
    log.Printf("Time %v", ed.Sub(st))
    return nil
}

例えば、下記の関数を計測するとする。

func GetHelloList(name string, count int) []string {
    var list []string
    for i:=0;i<count;i++ {
        list = append(list, fmt.Sprintf("Hello %s\n", name))
    }
    return list
}

BenchFuncSecondsの引数は(f func() errorなのでname string, count int)を引数に受け取り、[]stringを返り値に持つGetHelloListは一見計測できないように見える。

が、下記のように即時関数内func() errorで実行してやることで型の違いを気にせずに実行できるようになる。

func main() {
    _ = BenchFuncSeconds(func() error {
        _ = GetHelloList("Tarou", 99999)
        return nil
    })
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0