GotoBLAS2是一个高性能的数值计算矩阵库, 在测试GotoBLAS2库的时候, 想试试OpenMP的多线程跟单线程的运算速度的差别有多大.
1. 下载安装MinGW, 设置好环境变量;
2. 下载安装CodeBlocks(一个Windows下默认使用MinGW的C/C++ IDE环境), 并简单设置一下MinGW的路径;
3. 在MinGW环境下编译GotoBLAS2:
首先修改Makefile.rule, 设置为USE_OPENMP = 1, 把USE_THREAD = 0这句注释掉, 设置NUM_THREADS = 1, 或者注释掉这句, 大概原因是OpenMP不能跟pthread一起使用, 否则运算会很慢很慢, 整个系统卡死; 相反, 如果不使用OpenMP, 一定不要定义USE_OPENMP = 0, 要把该句注释掉, 因为定义了就代表使用OpenMP;
修改Makefile.system DUMMY中 $(MAKE) 为 make, 这样可以排除一些最终无法编译dll的问题;
使用命令 make BINARY=32 TARGET=CORE2 或 ./quickbuild.win32 编译
GotoBLAS2还有几个小bug, 一般是缺少C++所需要的extern "C"定义和防止头文件多次包含的预编译保护, 所以推荐使用国人改进的版本OpenBLAS;
如果动态支持CPU,使用 DYNAMIC_ARCH=1 (推荐打开, 但你可以尝试打开或关闭这个选项, 打开的话编译时间加长, 库文件大小也变大, 不过速度可能会提升);
修改一下内容
driver\others\dynamic.c
line 201 gotoblas = &gotoblas_KATMAI;
line 203 gotoblas = &gotoblas_PRESCOTT;
4. 在CodeBlocks里使用OpenMP:
开始写你的测试程序, 头文件里加上 #include <omp.h>,
然后再Compiler settings里面的Other Options里面填入-fopenmp
在Linker settings里面的Other linker Options里面填入-fopenmp -lgomp -lpthread (其中-lgomp -lpthread不一定是必须的, 你可以自己看情况决定)
如果在命令行下编译,可以使用命令
g++ -fopenmp main.cpp -lgomp -lpthread -o main.exe
由于我的测试代码太长, 不便贴出, 这里只是简单的示例:
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <common.h>
#include <cblas.h>
#include <time.h>
#include "gotoblas2.h"
using namespace std;
void eg_print()
{
#pragma omp parallel
printf ("[%d] Hello/n", omp_get_thread_num());
}
void eg_for()
{
#pragma omp parallel for
for(int i = 0; i <10; i++) {
printf("i = %d/n", i);
}
}
void eg_long_for()
{
int c = 0;
clock_t t1 = clock();
for(int i = 0; i <1000000000; i++) {
c++;
}
clock_t t2 = clock();
printf("Count = %d, t2 = %d, t1 = %d, Time = %d/n", c, t2, t1, t2-t1);
}
int main()
{
//eg_print();
//eg_for();
//测试
clock_t t1 = clock();
#pragma omp parallel for
for( int j = 0; j <2; j++ ) {
eg_long_for();
}
clock_t t2 = clock();
printf("Total time = %d/n", t2-t1);
eg_long_for();
return 0;
}