Chinaunix首页 | 论坛 | 博客
  • 博客访问: 403452
  • 博文数量: 77
  • 博客积分: 3149
  • 博客等级: 中校
  • 技术积分: 828
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-25 11:48
文章存档

2012年(5)

2011年(2)

2010年(11)

2009年(44)

2008年(15)

我的朋友

分类: LINUX

2009-06-16 18:15:44

 
 
/* Seriel Code */
#include
#include
#include
static long num_steps = 500000000;
double step;
int main()
{
int i;
double x, pi, sum = 0.0;
struct timeval start, finish;
double diffsec,diffusec;
gettimeofday(&start,NULL);
step = 1.0/(double) num_steps;
   for (i=0;i< num_steps; i++){
    x = (i+0.5)*step;
    sum = sum + 4.0/(1.0+x*x);
}
pi = step * sum;
    gettimeofday(&finish,NULL);
    diffsec=(double)finish.tv_sec-start.tv_sec;
    diffusec=(double)(finish.tv_usec-start.tv_usec)/(double)1000000;
    diffsec+=diffusec;
    printf("Cost time=%f second ,pi=%20.14lf\n",diffsec,pi);
    return 0;
}

/*parallel program with openmp*/
#include
#include
#include
#include
static long num_steps = 500000000;
double step;
#define NUM_THREADS 2
int main()
{
 int i;
 double x, sum, pi=0.0;
 struct timeval start, finish;
 double diffsec,diffusec;
 gettimeofday(&start,NULL);
 step = 1.0/(double) num_steps;
 omp_set_num_threads(NUM_THREADS);

#pragma omp parallel for private(x)  reduction(+:sum)
     for (i=0;i<= num_steps; i++){
     x = (i+0.5)*step;
     sum = sum + 4.0/(1.0+x*x);
}
    gettimeofday(&finish,NULL);
    diffsec=(double)finish.tv_sec-start.tv_sec;
    diffusec=(double)(finish.tv_usec-start.tv_usec)/(double)1000000;
    diffsec+=diffusec;
    printf("Cost time=%f second ,pi=%20.14lf\n",diffsec,sum/num_steps);
    return 0;
}

编译方法:gcc -fopenmp -o parallel openmp.c


阅读(2351) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-11-08 22:37:20

以上代码3有问题,不正确。正确写法参照: http://blog.chinaunix.net/u2/86537/showart_1964048.html