ループとマルチスレッドの両方が同じ操作を実行している場合、どちらが最も時間がかかりますか?
私のプログラムでは、マルチスレッドの実行時間がc langで最も長くなります
これは私のプログラムで、スレッド用の1つの関数とループ用のもう1つの関数です
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int ** A;
int ** B;
int ** C;
int ** D;
int k;
int r ;
clock_t begin_1, end_1, begin_2, end_2;
double time_spent_1, time_spent_2;
struct arguments{
int i;
int j;
int n;
};
void initialize(){
A = (int **)malloc(2*sizeof(int *));
int i;
for(i = 0; i<2; i++)
A[i] = (int*) malloc(2*sizeof(int));
B = (int **)malloc(2*sizeof(int *));
for(i = 0; i<2; i++)
B[i] = (int*)malloc(2*sizeof(int));
C = (int **)malloc(2*sizeof(int *));
for(i = 0; i<2; i++)
C[i] = (int*)malloc(2*sizeof(int));
D = (int **)malloc(2*sizeof(int *));
for(i = 0; i<2; i++)
D[i] = (int*)malloc(2*sizeof(int));
}
void generate(){
int i,j;
for (i=0; i<2; i++)
for (j=0; j<2; j++){
r = rand()%100;
A[i][j]=r;
}
for (i=0; i<2; i++)
for (j=0; j<2; j++){
r = rand()%100;
B[i][j]=r;
}
}
void mutip_1()
{
int i,j,temp,k;
begin_1 = clock();
for (i=0; i<2; i++){
for (j=0; j<2; j++){
temp = A[i][j];
for(k=0;k<2;k++){
C[i][k]+=temp*B[j][k];
}
}
}
end_1 = clock();
}
void* mul_mat(void* args)
{
struct arguments * temp = (struct arguments*) args;
int i = temp->i;
int j = temp->j;
int n = temp->n;
pthread_detach(pthread_self());
free(temp);
int k;
for(k=0;k<2;k++){
D[i][k]+=n*B[j][k];
}
pthread_exit(NULL);
}
int main(){
initialize();
generate();
mutip_1();
pthread_t* tid = (pthread_t*)malloc((2*2)*sizeof(pthread_t)); malloc((2*2)*sizeof(pthread_t));
int i, j,k=0;
int n;
begin_2 = clock();
for(i=0; i<2; i++){
for(j=0; j<2; j++){
n=A[i][j];
struct arguments *args=(struct arguments*)malloc((2*2)*sizeof(struct arguments));
args->i = i;
args->j = j;
args->n=n;
if (pthread_create(&tid[k++], NULL, (void*)mul_mat, (void*)args)){
perror("Thread Problem");
exit(1);
}
}
}
end_2 = clock();
time_spent_1 = (double)(end_1 - begin_1) / CLOCKS_PER_SEC;
time_spent_2 = (double)(end_2 - begin_2) / CLOCKS_PER_SEC;
printf("Matrix A: \n");
for (i=0; i<2; i++){
for (j=0; j<2; j++)
printf("%d ", A[i][j]);
printf("\n");
}
printf("Matrix B: \n");
for (i=0; i<2; i++){
for (j=0; j<2; j++)
printf("%d ", B[i][j]);
printf("\n");
}
printf("multiplication using loop: \n");
for (i=0; i<2; i++){
for (j=0; j<2; j++)
printf("%d ", C[i][j]);
printf("\n");
}
printf("multiplication using thread: \n");
for (i=0; i<2; i++){
for (j=0; j<2; j++)
printf("%d ", D[i][j]);
printf("\n");
}
printf("First time using loop %f \n", time_spent_1);
printf("second time using thread %f \n", time_spent_2);
return 0;
}