dtdb99743 2018-03-11 13:22
浏览 58
已采纳

如何使用标准库测试Go函数的执行时间

I've written the following function that when used with Defer will surely do the trick but is there something in standard library I could use for this? I'm looking something similar to Python timeit which I could use directly from the shell?

package main

import (
    "fmt"
    "time"
)

func main() {
    defer timeTrack(time.Now(), "looptest")
    nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    var m []int
    for n := range nums {
        if n%2 == 0 {
            m = append(m, n)
        }
    }
}

func timeTrack(start time.Time, name string) {
    elapsed := time.Since(start)
    fmt.Printf("%s took %s", name, elapsed)
}
  • 写回答

3条回答 默认 最新

  • dsgo31121 2018-03-11 13:40
    关注

    Use the Go testing package. For example,

    main.go:

    package main
    
    func doStuff() {
        nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        var m []int
        for n := range nums {
            if n%2 == 0 {
                m = append(m, n)
            }
        }
    }
    
    func main() {
        doStuff()
    }
    

    main_test.go:

    package main
    
    import "testing"
    
    func BenchmarkStuff(b *testing.B) {
        for i := 0; i < b.N; i++ {
            doStuff()
        }
    }
    

    Output:

    $ go test -bench=. -benchmem
    goos: linux
    goarch: amd64
    pkg: main
    BenchmarkStuff-4    5000000    276 ns/op    120 B/op    4 allocs/op
    

    Using the information from the benchmark, you can improve performance. Reduce the number and size of allocations by using an estimate to initialize slice m.

    func doStuff() {
        nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        m := make([]int, 0, len(nums)/2+1)
        for n := range nums {
            if n%2 == 0 {
                m = append(m, n)
            }
        }
    }
    

    Output:

    $ go test -bench=. -benchmem
    goos: linux
    goarch: amd64
    pkg: main
    BenchmarkStuff-4    20000000    83.1 ns/op    48 B/op    1 allocs/op
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真