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

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
❱ 

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