Created
November 7, 2015 05:09
-
-
Save hamadu/193959ef65a660bc1ce3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"os" | |
"strconv" | |
"runtime" | |
) | |
type Matrix [][]int | |
func computePart(i int, a, b, c *Matrix, ch chan int) { | |
ac := len((*a)[0]) | |
bc := len((*b)[0]) | |
for j := 0; j < bc; j++ { | |
part := 0 | |
for k := 0; k < ac; k++ { | |
part += (*a)[i][k] * (*b)[k][j] | |
} | |
(*c)[i][j] = part | |
} | |
ch <- 1 | |
} | |
func mulConcurrent(a, b *Matrix) Matrix { | |
ar := len(*a) | |
ac := len((*a)[0]) | |
br := len(*b) | |
bc := len((*b)[0]) | |
if ac != br { | |
panic("wrong matrix type") | |
} | |
c := make(Matrix, ar) | |
for i := 0 ; i < ar ; i++ { | |
c[i] = make([]int, bc) | |
} | |
ch := make(chan int) | |
for i := 0 ; i < ar ; i++ { | |
go computePart(i, a, b, &c, ch) | |
} | |
for i := 0 ; i < ar ; i++ { | |
<- ch | |
} | |
return c | |
} | |
func mul(a, b *Matrix) Matrix { | |
ar := len(*a) | |
ac := len((*a)[0]) | |
br := len(*b) | |
bc := len((*b)[0]) | |
if ac != br { | |
panic("wrong matrix type") | |
} | |
c := make(Matrix, ar) | |
for i := 0 ; i < ar ; i++ { | |
c[i] = make([]int, bc) | |
for j := 0 ; j < bc ; j++ { | |
for k := 0 ; k < ac ; k++ { | |
c[i][j] += (*a)[i][k] * (*b)[k][j] | |
} | |
} | |
} | |
return c | |
} | |
func main() { | |
n, _ := strconv.Atoi(os.Args[1]) | |
k, _ := strconv.Atoi(os.Args[2]) | |
runtime.GOMAXPROCS(k) | |
a := make(Matrix, n) | |
b := make(Matrix, n) | |
for i := 0 ; i < n ; i++ { | |
a[i] = make([]int, n) | |
b[i] = make([]int, n) | |
for j := 0 ; j < n ; j++ { | |
a[i][j] = rand.Intn(100) | |
b[i][j] = rand.Intn(100) | |
} | |
} | |
var c Matrix | |
if k == 0 { | |
c = mul(&a, &b) | |
} else { | |
c = mulConcurrent(&a, &b) | |
} | |
fmt.Println(c[0][0]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment