Different runtime duration with `go run` and `go build`

时间:2019-01-18 18:12:40

标签: go

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\n", elapsed)
}
❱ go run runtime.go 
2502263
Elapsed 133.893µs
❱ go build runtime.go 
❱ ./runtime 
2502263
Elapsed 402.435µs
❱ 

1 个答案:

答案 0 :(得分:1)

在Go中,我们不赞成毫无意义的微基准测试。如果要运行基准测试,请使用Go testing软件包。

例如,

输出:

$ 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
    }
}