Skip to content

Instantly share code, notes, and snippets.

@mgritter
Created March 22, 2020 20:12
Show Gist options
  • Save mgritter/dc3678b3c988e25eaf1629a416a8c0e9 to your computer and use it in GitHub Desktop.
Save mgritter/dc3678b3c988e25eaf1629a416a8c0e9 to your computer and use it in GitHub Desktop.
Memory locality profiling example
package main
import (
"fmt"
"math/rand"
)
func randArray(n int, maxVal int) [][]int {
a := make([][]int, n)
for i := range a {
row := make([]int, n)
a[i] = row
for j := range row {
row[j] = rand.Intn(maxVal + 1)
}
}
return a
}
func sumRowOrder(a [][]int) int {
total := 0
for _, row := range a {
for _, x := range row {
total += x
}
}
return total
}
func sumColumnOrder(a [][]int) int {
total := 0
size := len(a)
for x := 0; x < size; x++ {
for y := 0; y < size; y++ {
total += a[y][x]
}
}
return total
}
func main() {
n := 1000
a := randArray(n, 10)
fmt.Printf("sum = %d\n", sumRowOrder(a))
b := randArray(n, 10)
fmt.Printf("sum = %d\n", sumColumnOrder(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment