goroutine 的使用
我接触到 GO语言里的 goroutine 概念时的第一个想法就是做矩阵乘法时可以用到, 假设
C = AB
其中 A 是mxn 矩阵, B是 nxk 矩阵, C的元素Cij = A的第i行 与 B的第j列的内积。 因为每个Cij的计算都是独立的, 我们无需依次对Cij进行计算,可以并行地计算Cij, 在这种情形下, 完全可以用goroutine 来执行。
不用goroutine 的代码
这是不用 goroutine 的代码:
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)
}
}
// Use the C matrix
// ...
其中的 get_row() 和 get_column() 分别从矩阵中取出某一行或某一列;而 dot_product() 函数返回两个向量的内积。 注意C[i][j] 是依次计算的。
使用goroutine 的代码
这是使用goroutine 的代码, 调用 goroutine 很方便, 使用关键字 go 加上函数名就可以了:
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)
}(&c[i][j], ai, bj)
}
}
// Use the C matrix
// ...
我们看到, 原来的 c[i][j],_ = dot_product(ai, bj) 被一个匿名函数代替了。
但是我发现,如果在for循环之后使用C矩阵,发现它的元素并不正确。 原来, goroutine 的特点是它作为一个单独的执行线索被运行, 调用它的函数不会等它返回,而是立即go 语句后面的代码。 可能会出现这样的情况: 整个for循环都执行完了, 而个别的goroutine 还没有执行完, 这样C矩阵的值就不正确了。 我们需要一种同步机制,保证所有的goroutine 都执行完毕,代码再往下走。
wait group
wait group 能实现这种同步机制。 首先我们要import sync 模块。
import (
...
"sync" // use wati group
...
)
然后申明一个wait group 变量, 并根据 goroutine 的个数添加成员。 每个goroutine 结束前,调用Done () 函数,而调用goroutine 的函数用 Wait() 等待所有的gouroutine 完成。
var wg sync.WaitGroup // wait group
wg.Add(n*t) // number of goroutines
for i := 0; i < n; i++ {
ai,_ := get_row(a,i)
for j := 0; j < t; j ++ {
bj, _ := get_column(b,j)
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
// Use the C matrix
// ...
使用了这样的同步机制,就能保证C的元素都是正确的。
goroutine 真能节省时间吗
照我原来的理解, 在多核操作系统上, 多个 goroutine 是并行执行的,应该比不用goroutine 的代码节省时间。 因此我插入了一些benchmark 的代码:
var wg sync.WaitGroup // wait group
wg.Add(n*t) // number of goroutines
t1 := time.Now().UnixNano() //benchmark
for i := 0; i < n; i++ {
ai,_ := get_row(a,i)
for j := 0; j < t; j ++ {
bj, _ := get_column(b,j)
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)
我在计算开始和结束处获取两个时间 t1 和 t2, t2-t1 就是所花的时间,结果发现在矩阵为100x100的情况下, 使用goroutine 反而比不使用 goroutine 多花时间。 原来goroutine 也是有开销的, 在矩阵维数比较小的情况下, goroutine 的并行优势没有体现出来。 我把矩阵维数加到1000x1000, 此时使用goroutine 明显比不用goroutine 节省时间了。
使用pprof 来查看go程序的执行效率
我们还可以用pprof 模块来评测go程序的效率。 首先引入该模块和flag 模块:
import (
...
"flag"
"runtime/pprof"
)
flag 是为了分析命令行参数, 因为使用pprof 的时候要指定log文件。 在代码里插入:
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
...
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
如果指定了参数 cpuprofile , 我们就使能 pprof 的功能。 注意我们还使用了defer语句, 保证 pprof.StopCPUProfile() 函数在main 结束前调用。
在命令行上编译,并运行:
go build matrix.go
./matrix -cpuprofile=matrix.prof
go tool pprof matrix matrix.prof
我们先把go 源文件编译成执行文件, 然后调用 go的 pprof 工具, 此时我们进入了pprof 的交互式界面:
pprof 最重要的一个命令是topN, 其中N是数字, 显示
最花时间的前N个函数。 出乎我的意料, 最花时间的是get_column 函数, 该
函数返回矩阵的第k列。 get_column 比计算向量内积的函数 dot_product 花的时间还多。
get_column 是这样的函数, 从一个矩阵(即二维数组)里取出第k列:
// get the kth column of a matrix, return error if k > columns of the matrix
func get_column(a [][]int, k int)([]int , error) {
n,m := get_dimension(a)
if k >= m {
return nil, fmt.Errorf("%d is larger than the rows of matrix %d\n", k, m)
}
var c = make([]int, n)
for i := range c {
c[i] = a[i][k]
}
return c,nil
}
主要是数组操作, 居然比向量内积还耗时间? 这是dot_product 的代码:
func dot_product(a, b []int)(int, error) {
n := len(a)
m := len(b)
if n != m {
return 0, fmt.Errorf("the two vectors have different lengths\n")
}
sum := 0
for i := range a {
sum = sum + a[i] * b[i]
}
return sum, nil
}
这个现象只好暂时存疑了。