[英]How time executing depends of increasing of number of threads with using OpenMP library?
線程數量的增加會增加循環執行的時間,而會減少執行時間。
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <limits.h>
#define n 4
int main(int argc, char **argv)
{
FILE * file1 = fopen("output.txt", "w");
if (file1 == NULL){
exit(EXIT_FAILURE);
}
srand(time(NULL));
int matrix[n][n];
int i, j;
for(i = 0; i < n; i++){
for (j = 0; j < n; j++){
matrix[i][j] = rand() % 100 + 1;
fprintf(file1, "%d ", matrix[i][j]);
}
fprintf(file1, "\n");
}
int sum = 0;
int min;
double start;
double end;
啟動循環的時間
start = omp_get_wtime();
// in num_threads I've changed the number of threads
// and investigate a problem of increasing the time
#pragma omp parallel for private (i, j, min) reduction(+:sum) num_threads(4)
for(i = 0; i < n; i++){
min = INT_MAX;
for (j = 0; j < n; j++){
if(matrix[j][i] < min){
min = matrix[j][i];
}
}
sum += min; // sum of min numbers of each column
}
end = omp_get_wtime();
printf("Time: %lf\n", end - start);
printf("Min sum of matrix = %d", sum);
fclose(file1);
return 0;
}
4個線程
時間:0.000930
3線程
時間:0.000356
2線程
時間:0.000533
1個線程
時間:0.000008
我的CPU有4個線程。
您有一個非常小的問題(4x4),並且正在定時創建線程。 我認為並行性無論如何都不會在這種規模上有太大幫助(因為僅喚醒線程然后在並行結束時再次同步它們的開銷將比您嘗試做的工作大得多),但是您可以通過添加以下內容從度量中消除創建線程池的成本:
#pragma omp parallel ;
在定時區域之前。
並且,請,請,請不要強迫線程數。 使用OMP_NUM_THREADS
環境。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.