用golang写了例2的benchmark,的确像老师说的那样,ij方式要快! 速度比 102:9
Running tool: /usr/local/go/bin/go test -benchmem -run=^$ -bench ^(BenchmarkFor_IJ|BenchmarkFor_JI)$ -v
goos: darwin
goarch: amd64
BenchmarkFor_IJ-4 102 12360520 ns/op 1254901 B/op 0 allocs/op
BenchmarkFor_JI-4 9 113365872 ns/op 14222222 B/op 0 allocs/op
``` golang
package main
import "testing"
const n = 4000
func BenchmarkFor_IJ(b *testing.B) {
var arr [n][n]int
for c := 0; c < b.N; c++ {
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
arr[i][j] = i + j
}
}
}
}
func BenchmarkFor_JI(b *testing.B) {
var arr [n][n]int
for c := 0; c < b.N; c++ {
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
arr[j][i] = i + j
}
}
}
}
```
展开