写一个生成二维随机数数组的openmp程序:
#include "mex.h"
#include
#include
#include
void calc(double * p, int n)
{
omp_set_num_threads(8);
int i;
#pragma omp parallel for //private(i)
for (i = 0; i
{
p[i] = i;
//printf("i = %d, Thread = %d\n", i, omp_get_thread_num());
}
}
void rand(double * p, int n)
{
srand(( unsigned int )time(NULL));
omp_set_num_threads(4);
int i;
#pragma omp parallel for
for(i = 0; i < n; ++i)
{
p[i] = rand()%256;
//printf("i = %d, Thread = %d\n", i, omp_get_thread_num());
}
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mxAssert(nlhs == 1 && nrhs == 1, "Error:The output/input array should be only one");
mxAssert(mxGetM(prhs[0]) == 1 && mxGetN(prhs[0]) == 2, "Error: cols and rows");
double* p_in = static_cast (mxGetData(prhs[0]));
int m = static_cast< int >(p_in[0]);
int n = static_cast< int >(p_in[1]);
plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL);
double* dynamicData = static_cast (mxGetData(plhs[0]));
//calc(dynamicData, m*n);
rand(dynamicData, m*n);
//mxSetData(plhs[0], dynamicData);
}
编译生成可执行的mex文件:
>> mex COMPFLAGS="$COMPFLAGS -openmp" rand2D.cpp
生成300*300的随机数数组:
>> tic;rand2D([300, 300]);toc
Elapsed time is 0.188277 seconds.
使用MATLAB内部函数randint()生成随机数数组:
>> tic;randint(300, 300, [0, 256]);toc;
Elapsed time is 0.653515 seconds.
可以看出在设置线程数为4的情况下,与MATLAB内部函数randint()相比,openmp程序的性能为4倍。