drpmazn9021
2019-01-18 18:12
浏览 10
已采纳

“运行”和“构建”的运行时间不同

Why does the runtime of my program change when I use go run vs go build and executing my program?

I'm using the time package to measure the time elapsed during program execution, and I stumbled upon this behaviour.

package main

import (
    "fmt"
    "io/ioutil"
    "time"
)

func sumInt(b []byte, c chan int) {
    sum := 0
    for _, num := range b {
        sum += int(num)
    }
    c <- sum
}

func main() {
    start := time.Now()

    dat, err := ioutil.ReadFile("nums.txt")
    if err != nil {
        return
    }

    partSum1 := make(chan int)
    partSum2 := make(chan int)

    go sumInt(dat[:len(dat)/2], partSum1)
    go sumInt(dat[len(dat)/2:], partSum2)

    sum := <-partSum1 + <-partSum2
    fmt.Println(sum)

    elapsed := time.Since(start)
    fmt.Printf("Elapsed %s
", elapsed)
}
❱ go run runtime.go 
2502263
Elapsed 133.893µs
❱ go build runtime.go 
❱ ./runtime 
2502263
Elapsed 402.435µs
❱ 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duankuaizhe8257 2019-01-18 21:24
    已采纳

    In Go, we don't favor meaningless microbenchmarks. If you are going to run a benchmark, use the Go testing package.

    For example,

    Output:

    $ go test sum_test.go -bench=. -benchmem
    goos: linux
    goarch: amd64
    BenchmarkSum-8    500000    2905 ns/op    4288 B/op    3 allocs/op
    $
    

    sum_test.go:

    package main
    
    import (
        "testing"
    )
    
    func sumInt(b []byte, c chan int) {
        sum := 0
        for _, num := range b {
            sum += int(num)
        }
        c <- sum
    }
    
    func BenchmarkSum(b *testing.B) {
        for N := 0; N < b.N; N++ {
            dat := make([]byte, 4*1024)
            partSum1 := make(chan int)
            partSum2 := make(chan int)
            go sumInt(dat[:len(dat)/2], partSum1)
            go sumInt(dat[len(dat)/2:], partSum2)
            sum := <-partSum1 + <-partSum2
            _ = sum
        }
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题