#include
#include
long long add(int x,int y){ //单线程计算函数 long long sum; for(;x<=y;x++)sum+=x; return sum; } long long ADD(int x,int y){ //多线程计算函数 long long s1,s2,s3,s4,s5,sum; int temp=y/5; #pragma omp parallel sections { #pragma omp section s1=add(1,temp); #pragma omp section s2=add(temp+1,2*temp); #pragma omp section s3=add(2*temp+1,3*temp); #pragma omp section s4=add(3*temp+1,4*temp); #pragma omp section s5=add(4*temp+1,y); } sum=s1+s2+s3+s4+s5; return sum; } void main(){ double start,end; printf("计算1+2+...+:\n"); start = omp_get_wtime(); printf("单线程计算结果为:%lld\n",add(1,)); end = omp_get_wtime(); printf("单线程用时:%fs\n",(end - start)); start = omp_get_wtime(); printf("多线程计算结果为:%lld\n",ADD(1,)); end = omp_get_wtime(); printf("多线程用时:%fs\n",(end - start)); }
运行结果:

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/177607.html原文链接:https://javaforall.net
