I am playing around with some elementary timing in Go and have a question. I want to time Golang in taking the square root of each element of an array but I get two somewhat different answers whether or not I keep the output. Here is the my first version:
package main
import ("fmt"
"time"
"math"
"math/rand"
)
// A random array of integers
func randomArray(max int ,len int) []int {
a := make([]int, len)
for i := 0; i <= len-1; i++ {
a[i] = rand.Intn(max)
}
return a
}
// Taking square root of each element in array
func sqrt_array(arr [] int) [] float64 {
var len_arr = len(arr)
a := make([]float64, len_arr)
for i, v := range arr {
a[i] = math.Sqrt(float64(v))
}
return a
}
func main() {
arr := randomArray(100, 10e6)
sqrt := make([]float64, len(arr))
start := time.Now()
sqrt = sqrt_array(arr)
end := time.Now()
fmt.Println("time taken: ", end.Sub(start), sqrt[0])
}
gives on average around 36ms:
time taken: 36.542019ms 9
Now when I replace the output "sqrt" with the blank identifier, I get something much slower. Specifically, I replace main() with
func main() {
arr := randomArray(100, 10e6)
// sqrt := make([]float64, len(arr))
start := time.Now()
_ = sqrt_array(arr)
end := time.Now()
fmt.Println("time taken: ", end.Sub(start))
}
and get on average something like 92ms
time taken: 92.121481ms
Would someone be able to explain what is happening? I feel that if I understood I might learn something about Go.
Incidentally I find that the same computation in Python was around 20ms if broadcasted and several hundred ms if in a loop.