> I believe this is simply due to the 64 bits integer division.
>
> 1. Contrary to Java or most C implementations int is 64 bits with Go on
> AMD64, and not 32 bits. Integer division on 64 bits is more expensive than
> for 32 bits.
> 2. When array_length is known at compile time, the compiler can replace
> the integer division done for % with cheaper operations.
>
Well, the compile-time-constant program did not become slower with int64,
but the run-time-value program did become faster with int32 —
package main
import "os"
import "fmt"
import "strconv"
func main() {
var (
element, iteration, iterations, innerloop int64
sum float64
)
if len(os.Args) > 1 {
var i,_ = strconv.Atoi(os.Args[1])
iterations = int64(i)
}
fmt.Printf("iterations %d\n", iterations)
var (
array_length int64 = 100000000
array []float64 = make([]float64, array_length)
)
for element = 0; element < array_length; element++ {
array[element] = float64(element)
}
for iteration = 0; iteration < iterations; iteration++ {
for innerloop = 0; innerloop < 1000000000; innerloop++ {
sum += array[(iteration + innerloop) % array_length]
}
}
fmt.Printf("sum %E\n", sum)
array = nil
}
$ /opt/src/go1.16/go/bin/go build -o out test.go
$ time ./out 100
iterations 100
sum 5.000000E+18
real 3m3.240s
====
package main
import "os"
import "fmt"
import "strconv"
func main() {
var (
element, iteration, iterations, innerloop int32
sum float64
)
if len(os.Args) > 1 {
var i,_ = strconv.Atoi(os.Args[1])
iterations = int32(i)
}
fmt.Printf("iterations %d\n", iterations)
var (
array_length int32 = 1000000 * iterations
array []float64 = make([]float64, array_length)
)
for element = 0; element < array_length; element++ {
array[element] = float64(element)
}
for iteration = 0; iteration < iterations; iteration++ {
for innerloop = 0; innerloop < 1000000000; innerloop++ {
sum += array[(iteration + innerloop) % array_length]
}
}
fmt.Printf("sum %E\n", sum)
array = nil
}
$ /opt/src/go1.16/go/bin/go build -o out test.go
$ time ./out 100
iterations 100
sum 5.000000E+18
real 6m57.880s
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/55776153-c06f-40d0-a926-08592a973e67n%40googlegroups.com.