如果循环和多线程都执行相同的操作 哪一个会花费最长的时间?
在我的程序中,多线程的执行时间最长 在c lang
这是我的程序一个用于线程的函数,另一个用于for循环
#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;
}
答案 0 :(得分:1)
我之间
for i=1 to 50
do something
next i
和II
for i=1 to 50
create thread that does the same something
next i
如果II计算可以并行运行,理论结果是
答案 1 :(得分:0)
由于系统调用和线程间通信,线程创建和/或向线程池发出任务会产生相当大的开销,因此,在多核CPU上:
矩阵的维数= 2,在一个线程中循环更快。
矩阵的维数= 2000000,更快地在多个线程中循环。
总结:不要解决微不足道的CPU密集型操作。