I am trying to figure out the best practices regarding performance.
(我正在尝试找出有关性能的最佳做法。)
I have noticed that specifying integer types for a for-loop could effect the performance drastically (x2 times in my case). (我注意到为for循环指定整数类型可能会极大地影响性能(在我的情况下为x2倍)。)
My question is, is it supposed to be that using the int64 would be much slower than using int32 or I am missing something in my code?
(我的问题是,是否应该认为使用int64比使用int32慢得多,或者我的代码中缺少某些内容?)
The code I am using:
(我正在使用的代码:)
a.go
(前)
package main
import (
"fmt"
"time"
"runtime"
"strconv"
)
func main() {
start := time.Now()
var x1 int // later change all int to int32 or int64
for i := int(0); i <= int(1000000000); i++ {
x1 = x1 + i
}
t := time.Now()
elapsed := t.Sub(start)
fmt.Println(x1)
fmt.Println(elapsed)
fmt.Println(runtime.Compiler, runtime.GOARCH, runtime.GOOS)
fmt.Println(strconv.IntSize)
}
Output using int32 for x1
(使用int32输出x1)
C:...>go build a.go
C:...>a
-243309312
238.3333ms
gc amd64 windows
64
Output using int64 for x1
(使用x1的int64输出)
C:...>go build a.go
C:...>a
500000000500000000
467.7835ms
gc amd64 windows
64
Update
(更新资料)
I tried @Giulio Micheloni suggestion and got more accurate benchmark.
(我尝试了@Giulio Micheloni的建议,并获得了更准确的基准。)
goos: windows
goarch: amd64
BenchmarkInt64-12 1000000000 0.234 ns/op 0 B/op 0 allocs/op
PASS
ok _/c_/.../.../Desktop 0.402s
Success: Benchmarks passed.
goos: windows
goarch: amd64
BenchmarkInt32-12 1000000000 0.231 ns/op 0 B/op 0 allocs/op
PASS
ok _/c_/.../.../Desktop 0.403s
Success: Benchmarks passed.
ask by Kingindanord translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…