// Sum_section.cpp : 定义控制台应用程序的入口点。
//section功能:;
//1.指定其内部的代码划分给线程中某个线程,不同的section由不同的线程执行;
//2.将一个任务划分成独立的几个section,且section之间是并行执行的; #include "stdafx.h" //#include <stdio.h>
#include <time.h>
#include "omp.h"
#include <windows.h> #define NUM_THREADS 2
#define num 1000000000
int _tmain(int argc, _TCHAR* argv[])
{
omp_set_num_threads(NUM_THREADS);
long long sum=0;
clock_t t1=clock();
#pragma omp parallel sections reduction(+:sum)//reduction解决数据竞争,将两个线程所得的sum加起来
{
#pragma omp section
{
for (long i=omp_get_thread_num();i<=num;i=i+NUM_THREADS)
{
sum=sum+i;
}
}
#pragma omp section
{
for (long i=omp_get_thread_num();i<=num;i=i+NUM_THREADS)
{
sum=sum+i;
}
} }
clock_t t2=clock();
clock_t parallel=t2-t1;
printf("sum=%lld\n",sum);
printf("parallel time=%d\n\n",parallel); //串行
sum=0; t1=clock();
for(long long i=1;i<=num;i=i+1)
{
sum=sum+i;
}
t2=clock();
clock_t serial=t2-t1;
printf("sum=%lld\n",sum);
printf("serial time=%d\n",serial); system("pause");
return 0;
} //运行结果如下:相对加速比为:2981/1643=1.81