Skip to content

Instantly share code, notes, and snippets.

@tebeka
Created March 8, 2020 07:39
Show Gist options
  • Save tebeka/0e694ee91e7f59a6999a8bc4a7d9d5d5 to your computer and use it in GitHub Desktop.
Save tebeka/0e694ee91e7f59a6999a8bc4a7d9d5d5 to your computer and use it in GitHub Desktop.
Matrix Sum
package main
import (
"testing"
)
var (
nRows, nCols = 10000, 27
mat [][]int
n = nRows * nCols
// sum of algebraic series
sum = n / 2 * (0 + (n - 1))
)
func init() {
mat = make([][]int, nRows)
for r := 0; r < nRows; r++ {
row := make([]int, nCols)
for c := 0; c < nCols; c++ {
row[c] = r*nCols + c
}
mat[r] = row
}
}
func sumByRows(m [][]int) int {
total := 0
for r := range m {
for c := range m[0] {
total += m[r][c]
}
}
return total
}
func BenchmarkRows(b *testing.B) {
for i := 0; i < b.N; i++ {
s := sumByRows(mat)
if s != sum {
b.Fatalf("%v != %v", sum, s)
}
}
}
func sumByCols(m [][]int) int {
total := 0
for c := range m[0] {
for r := range m {
total += m[r][c]
}
}
return total
}
func BenchmarkCols(b *testing.B) {
for i := 0; i < b.N; i++ {
s := sumByCols(mat)
if s != sum {
b.Fatalf("%v != %v", sum, s)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment