// MatrixCalcTest project main.go
package main
import (
"fmt"
"time"
)
const cSize int = 30
type mymatrix [cSize][cSize]int
func mkmatrix(rows, cols int, mx *mymatrix) {
rows--
cols--
count := 1
for r := 0; r <= rows; r++ {
for c := 0; c <= cols; c++ {
mx[r][c] = count
count++
}
}
}
func multmatrix(rows, cols int, m1, m2 *mymatrix, mm *mymatrix) {
rows--
cols--
for i := 0; i <= rows; i++ {
for j := 0; j <= cols; j++ {
val := 0
for k := 0; k <= cols; k++ {
val += m1[i][k] * m2[k][j]
mm[i][j] = val
}
}
}
}
func main() {
var m1, m2, mm mymatrix
mkmatrix(cSize, cSize, &m1)
mkmatrix(cSize, cSize, &m2)
t0 := time.Now()
for i := 0; i <= 100000; i++ {
multmatrix(cSize, cSize, &m1, &m2, &mm)
}
t := time.Since(t0)
fmt.Println(mm[0][0], mm[2][3], mm[3][2], mm[4][4], mm[29][29])
fmt.Println("tick = ", t)
}VC++:// MatrixCalcTest.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <Windows.h>#include <iostream>using namespace std;const int MATRIX_SIZE = 30;int Matrix[MATRIX_SIZE][MATRIX_SIZE];void MakeMatrix(int rows, int cols, int mx[MATRIX_SIZE][MATRIX_SIZE]){ rows--; cols--; int count = 1; for (int r = 0; r <= rows; r++) { for (int c = 0; c <= cols; c++) { mx[r][c] = count; count++; } }}void MatrixMult(int rows, int cols, const int m1[MATRIX_SIZE][MATRIX_SIZE], const int m2[MATRIX_SIZE][MATRIX_SIZE], int mx[MATRIX_SIZE][MATRIX_SIZE]){ rows--; cols--; int val; for (int i = 0; i <= rows; i++) { for (int j = 0; j <= cols; j++) { val = 0; for (int k = 0; k <= cols; k++) { val += m1[i][k] * m2[k][j]; mx[i][j] = val; } } }}int _tmain(int argc, _TCHAR* argv[]){ int num = 100000; int m1[MATRIX_SIZE][MATRIX_SIZE], m2[MATRIX_SIZE][MATRIX_SIZE], mx[MATRIX_SIZE][MATRIX_SIZE]; MakeMatrix(MATRIX_SIZE, MATRIX_SIZE, m1); MakeMatrix(MATRIX_SIZE, MATRIX_SIZE, m2); UINT tick = GetTickCount(); for (int i = 0; i <= num; i++) { MatrixMult(MATRIX_SIZE, MATRIX_SIZE, m1, m2, mx); } tick = GetTickCount() - tick; cout << mx[0][0] << " " << mx[2][3] << " " << mx[3][2] << " " << mx[4][4] << " " << mx[29][29] << endl; cout << tick << " ms" << endl; cin >> tick; return 0;}
go默认是有数组边界检查,可以关掉的
go build -gcflags "-B"
关掉后我这里大概快了15%~20%
另外编译64位win的又快了15%~20%
最初是8.9秒左右(32位,未关闭边界检查)
然后是7.3秒左右(32位,关闭边界检查)
最后是6.2秒左右(64位,关闭边界检查)
未改动其他代码,cpu e3-1230v3 win7x64
这种情况下2-3倍的效率差距完全可以接受..
=================================
以上应该是go1.3的结果
今天更新了1.4又试了下,又快了10%
关闭边界检查的话在5.6秒这样
有疑问加站长微信联系(非本文作者)