#include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #define SIZEOFMAT 1000 #define SIZEOFVEC 10000000
int seq[SIZEOFMAT]; int* rets[SIZEOFMAT];
static void* calc(void *input) { int rowNum = *(int*)input; int *sum = malloc(sizeof(int)); *sum = 0; for (int i = 0; i < SIZEOFVEC; i++) { *sum+=1; } return (void*)sum; }
int main() { clock_t start,end; pthread_t ids[SIZEOFMAT]; int outVec[SIZEOFMAT]; for (int i = 0; i < SIZEOFMAT; i++) { seq[i] = i; } start = clock(); for (int i = 0; i < SIZEOFMAT; i++) { int ret = pthread_create(ids+i, NULL, calc, (void*)(seq+i)); if(ret) { printf("创建发生错误!"); exit(0); } } for (int i = 0; i<SIZEOFMAT;i++) { pthread_join(ids[i], (void**)(rets+i)); } for(int i = 0;i<SIZEOFMAT;i++) { free(rets[i]); } end = clock(); printf("并行计算经过的时间为 %d\n", end-start);
start = clock(); int sumSeq[SIZEOFMAT] = {0}; for(int i = 0;i<SIZEOFMAT; i++) { for(int j = 0;j<SIZEOFVEC; j++) { sumSeq[i]+=1; } } for(int i = 0;i<SIZEOFMAT;i++) { } end = clock(); printf("循环计算经过的时间为:%d\n", end - start); }
|