参考
https://blog.csdn.net/lusongno1/article/details/82929596
工具文档
https://www.hz-bin.cn/OpenMP
在OpenMP中
omp_get_num_procs()函数来获取默认最大可用线程个数,
omp_get_thread_num()函数来获得每个线程的ID,为了使用这两个函数,我们需要include <omp.h>
另外,omp_get_num_threads()返回当前并行区域中的活动线程个数,如果在并行区域外部调用,返回1。
omp_set_num_threads(5)设置进入并行区域时,将要创建的线程个数为5个。在指导语句中直接设置核心数也是可以的:#pragma omp parallel num_threads(6)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
#include<iostream>
#define m 2000
int a[m][m];
int b[m][m];
int c[m][m];
int main() {
clock_t start, end;
int i, j, k;
// srand((unsigned)time(NULL));//根据时间来产生随机数种子
srand(0);
for (i = 0; i < m; i++) {
for (j = 0; j < m; j++) {
a[i][j] = (int)rand() / (RAND_MAX);//产生[0,1]随机数
b[i][j] = (int)rand() / (RAND_MAX);
c[i][j] = 0;//初始化c矩阵用来存结果
#if m <= 1 //打印一下呗
printf("%f ", a[i][j]);
if (j == m - 1) {
printf("\n");
}
#endif
}
}
// int gettimeofday(struct timeval*tv, struct timezone *tz);
omp_set_num_threads(8);
int pnum = omp_get_num_procs();//获取系统默认最大线程数量
fprintf(stderr, "Thread_pnum = %d\n", pnum);
// gettimeofday(&st, NULL);
start = clock();
#pragma omp parallel shared(a,b,c) private(j,k)
{
#pragma omp for nowait //schedule(static)
for (i = 0; i < m; i++) {
for (j = 0; j < m; j++) {
for (k = 0; k < m; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
std::cout <<"thread id: "<< omp_get_thread_num() <<" time: "<< clock() << "\n";
}
end = clock();
printf("matrix multiply time: %0.6lf sec\n", ((double)end - start) / CLK_TCK);
return 0;
}
使用nowait语句
没有使用nowait语句