1、实验目标
(1) 利用visual studio 2017配置OpenMP环境;
打开VisualStudio 2017菜单栏->文件->新建->项目:新建Visual C++工程 :Windows控制台应用程序
Figure 1 新建Parallel_Lab1_Martrix-Vecter项目
打开菜单栏->项目->Parallel_Lab1_Martrix-Vecter(视自己新建项目名,最下面一栏)属性->配置属性->C/C++->语言->OpenMp 支持:选择是(/openmp)。(这一步是为了支持openmp。)点击“应用”。
Figure 2 打开项目的OpenMP支持
打开菜单栏->项目->属性-> Parallel_Lab1_Martrix-Vecter(视自己新建项目名,最下面一栏)属性->配置属性->代码生成—>运行库:选择多线程调试(/Mtd)。(这一步是为了支持多线程。)点击“应用”。
Figure 3 打开项目的多线程支持
打开菜单栏->项目->属性-> Parallel_Lab1_Martrix-Vecter(视自己新建项目名,最下面一栏)属性->配置属性->调试->命令参数: 在空白栏填入main函数的输入参数(argv[i]的值)。如需多个参数,用空格分隔每个参数,此处暂编辑输入“12”。
Figure 4 设置main函数的输入参数
(2)对以下算法利用OpenMP实现并行化。
i. Martrix-Vecter 乘法;
ii梯形积分法;
Figure 5 梯形积分法示意图
iii奇偶变换排序
2、串行程序代码
Martrix-Vector乘法:
- Function: Mat_vect_mult
- Purpose: Multiply a matrix by a vector
- In args: A: the matrix
- x: the vector being multiplied by A
- m: the number of rows in A and components in y
- n: the number of columns in A components in x
- Out args: y: the product vector Ax
/*------------------------------------------------------------------ void Mat_vect_mult(double A[] /* in */, double x[] /* in */, double y[] /* out */,int m /* in */, int n /* in */) {int i, j;for (i = 0; i < m; i++) {y[i] = 0.0;for (j = 0; j < n; j++)y[i] += A[i*n+j]*x[j];}
} /* Mat_vect_mult */
*/
梯形积分法:
/*------------------------------------------------------------------* Function: Trap* Purpose: Estimate integral from a to b of f using trap rule and* n trapezoids* Input args: a, b, n, h* Return val: Estimate of the integral */
double Trap(double a, double b, int n, double h) {double integral;int k;integral = (f(a) + f(b))/2.0;for (k = 1; k <= n-1; k++) {integral += f(a+k*h);}integral = integral*h;return integral;
} /* Trap *//*------------------------------------------------------------------* Function: f* Purpose: Compute value of function to be integrated* Input args: x*/
double f(double x) {double return_val;return_val = x*x;return return_val;
} /* f */
奇偶变换排序:
/*-----------------------------------------------------------------* Function: Odd_even_sort* Purpose: Sort list using odd-even transposition sort* In args: n* In/out args: a*/
void Odd_even_sort(int a[] /* in/out */, int n /* in */) {int phase, i, temp;for (phase = 0; phase < n; phase++) if (phase % 2 == 0) { /* Even phase */for (i = 1; i < n; i += 2) if (a[i-1] > a[i]) {temp = a[i];a[i] = a[i-1];a[i-1] = temp;}} else { /* Odd phase */for (i = 1; i < n-1; i += 2)if (a[i] > a[i+1]) {temp = a[i];a[i] = a[i+1];a[i+1] = temp;}}
} /* Odd_even_sort */