On Fri, Feb 19, 2021 at 6:46 AM Yuwen Dai <yuw...@gmail.com> wrote:
>
> I'm a newbie to golang.  One of my first ideas to use goroutine is to write a 
> matrix multiplying programme:  C = A*B.    I though the calculating of  every 
> element of C:  c[i][j] = row i of A  *  column j of B could be run by a 
> goroutine.  This is the skeleton of the code:
>
>     t1 := time.Now().UnixNano()  //benchmark
>     rand.Seed(t1)
>     for i := 0; i < n; i++ {
>         ai,_ := get_row(a,i)
>         for j := 0; j < t; j ++ {
>             bj, _ := get_column(b,j)
>             //        c[i][j],_ = dot_product(ai, bj)
>             go func(element *int, ai,bj []int) {
>                 *element,_ = dot_product(ai,bj)
>                 wg.Done()
>             }(&c[i][j], ai, bj)
>         }
>     }
>
>     wg.Wait()  // waiting for all the elements have been calculated
>     t2 := time.Now().UnixNano()
>     fmt.Printf("the dot_product using goroutine costs %v\n", t2 - t1)
>
> As the goroutines will run "concurrently" on my laptop with 8 CPU cores to 
> calculate the element of matrix, I thought the code would ran faster than not 
> using goroutine.  In fact, it ran slowlier than not using goroutine.  Any 
> explanation of this?    By the way,  the dimension of  matrix is 100x100.

Goroutines are lightweight but they are not free.  On the other hand,
modern CPUs do simple additions and multiplications very quickly.  The
cost of starting and waiting for a goroutine is larger than the cost
of a few multiplications.  Your goroutine version might run faster if
the matrix is very very very large, but for practical matrixes it will
be faster to do just do the arithmetic sequentially.

Ian

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcWDLKeX2CPY4Ozb%2B%2BXza91E-E2z_L1sqjBD-x9vpjn9GA%40mail.gmail.com.

Reply via email to