gpt4 book ai didi

performance - 使用int64而不是int32时,for循环性能要慢得多

转载 作者:行者123 更新时间:2023-12-01 20:23:23 57 4
gpt4 key购买 nike

我正在尝试找出有关性能的最佳做法。
我注意到,为for循环指定整数类型可能会极大地影响性能(在我的情况下为x2倍)。

我的问题是,是否应该认为使用int64比使用int32慢得多,或者我的代码中缺少某些内容?

我正在使用的代码:

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

使用int32输出x1

C:\...>go build a.go
C:\...>a

-243309312
238.3333ms
gc amd64 windows
64

使用int64输出x1

C:\...>go build a.go
C:\...>a

500000000500000000
467.7835ms
gc amd64 windows
64

更新

我尝试了@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.

最佳答案

毫无意义的微基准测试将产生毫无意义的结果。

The Go Programming Language Specification

Numeric types

int32   set of all signed 32-bit integers 
(-2147483648 to 2147483647)
int64 set of all signed 64-bit integers
(-9223372036854775808 to 9223372036854775807)

Arithmetic operators

Integer overflow

For signed integers, the operations +, -, *, /, and << may legally overflow and the resulting value exists and is deterministically defined by the signed integer representation, the operation, and its operands. Overflow does not cause a run-time panic.



溢出!
package main

import (
"fmt"
"math"
"runtime"
"strconv"
"time"
)

func main() {
start := time.Now()
var x1 int32 // later change all int to int32 or int64

for i := int32(0); i <= int32(1000000000); i++ {

if int64(x1)+int64(i) > math.MaxInt32 {
fmt.Println("Overflow:", x1, "+", i, "=", x1+i)
break
}

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

游乐场: https://play.golang.org/p/bdhB4ABf7jY

输出:
Overflow: 2147450880 + 65536 = -2147450880
gc amd64 linux
64

关于performance - 使用int64而不是int32时,for循环性能要慢得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59121187/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com