mit-ocw

Source code for MIT-OCW coursework
git clone git://git.laack.co/mit-ocw.git
Log | Files | Refs

mat_mul_parallel.go (810B)


      1 package main
      2 
      3 import (
      4 	"fmt"
      5 	"math/rand"
      6 	"sync"
      7 	"time"
      8 )
      9 
     10 const n = 400
     11 
     12 func randInit(arr [n][n]float32) [n][n]float32 {
     13 
     14 	for i := range len(arr) {
     15 		for j := range len(arr[i]) {
     16 			arr[i][j] = rand.Float32()
     17 		}
     18 	}
     19 
     20 	return arr
     21 
     22 }
     23 
     24 func compute(A *[n][n]float32, B *[n][n]float32, C *[n][n]float32, i int, wg *sync.WaitGroup) {
     25 
     26 	for k := range B {
     27 		for j := range B {
     28 			C[i][j] += A[i][k] * B[k][j]
     29 		}
     30 	}
     31 
     32 	wg.Done()
     33 }
     34 
     35 func main(){
     36 
     37 
     38 	A := [n][n]float32{}
     39 	B := [n][n]float32{}
     40 	C := [n][n]float32{}
     41 
     42 
     43 	A = randInit(A)
     44 	B = randInit(B)
     45 
     46 	start := time.Now()
     47 
     48 	var wg sync.WaitGroup
     49 
     50 	for i := range A {
     51 		wg.Add(1)
     52 		go compute(&A, &B, &C, i, &wg)
     53 	}
     54 
     55 	wg.Wait()
     56 
     57 	end := time.Now()
     58 
     59 	fmt.Println(end.Sub(start).Seconds())
     60 }
     61 
     62 // This runs in:
     63 
     64 // 1: 0.013814715
     65 // 2: 0.015052904
     66 // 3: 0.013208566