今天在做課程實驗時,用蒙特卡洛演算法求pai,要求通過使用pthread來提升性能,結果使用了多執行緒后,運行時間比單執行緒更長,求求大佬們幫助!
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
# include <time.h>
# include <pthread.h>
long long sum = 100000000;
long long num_circle = 0;
int thread_count;
void * compute(void * rank);
int main(int argc , char * argv[]){
long thread;
pthread_t* thread_handlers;
//讀取執行緒數
thread_count = strtol(argv[1],NULL,10);
// printf("%d\n",thread_count);
//獲取執行緒記憶體空間
thread_handlers = malloc(thread_count * sizeof(pthread_t));
clock_t start, end;
//開始計時
start = clock();
//初始化亂數種子
srand(time(0));
//創建thread_count個執行緒
for(thread = 0;thread < thread_count;thread ++){
pthread_create(& thread_handlers[thread], NULL, compute, (void*) thread);
}
//合并thread_count個執行緒
for(thread = 0;thread < thread_count;thread ++){
pthread_join(thread_handlers[thread],NULL);
}
free(thread_handlers);
//結束計時
end = clock();
//計算用時
double duaration = (double)(end - start)/CLOCKS_PER_SEC;
double pai = num_circle *1.0 / sum *4;
printf("finished in %f seconds\n %f",duaration,pai);
}
void* compute(void* rank){
long my_rank = (long) rank;
int my_start = my_rank * (sum / thread_count);
int my_end = (my_rank + 1) * (sum / thread_count) - 1;
for(int i = my_start;i <= my_end;i ++){
double x = 2.0*rand()/RAND_MAX-1;
double y = 2.0*rand()/RAND_MAX-1;
double distance_squared = sqrt(x * x + y * y);
if(distance_squared <= 1.0){
num_circle ++;
}
}
// printf("%f\n",distanc_squared);
return rank;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/57246.html
標籤:分布式計算/Hadoop
上一篇:Idea中Maven下的Generate Sources and update folders for all projects選項是干嘛用的???
下一篇:論自信得影響
