Linux下计算pai

双线程计算pai

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#define N 1000000000
double pai = 0.0, sum = 0.0;
double step = 1.0/(double)N;
void *count_thread(void)
{
    int i;
    double x, temp;
    for(i = 0; i < N / 2; i ++)
    {
        x = (i + 0.5) * step;
        temp = (4.0 / (1.0 + x *x));
        pai += temp;
    }
}
int main()
{
    pthread_t child_thread;
    int i;
    struct timeval start_time, end_time;
        double x, temp, tempsum;
    double spend_time;
    gettimeofday(&start_time, NULL);
    pthread_create(&child_thread, NULL, count_thread, NULL);
        for(i = N / 2; i < N; i++)
        {
        x = (i + 0.5) * step;
        temp = (4.0 / (1.0 + x * x));
            tempsum += temp;
        }
    sum += tempsum;
    pthread_join(child_thread,NULL);
        pai = pai + sum;
    printf("PAI = %12.9f\n", pai * step);
    gettimeofday(&end_time, 0);
    spend_time = 1000000*(end_time.tv_sec - start_time.tv_sec)+end_time.tv_usec - start_time.tv_usec;
    spend_time /= 1000000;
    printf("It takes %f seconds to calculate PI.\n",spend_time);
    exit(0);
}

单线程计算pai

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#define N 1000000000
int main()
{
    double pai = 0.0;
    double step, x, temp, spend_time;
    int i;
    struct timeval start_time, end_time;
    gettimeofday(&start_time, NULL);
    step = 1 / (double)N;
    for(i = 0; i < N; i++)
    {
    x = (i + 0.5) * step;
    temp = (4.0 / (1.0 + x * x));
    pai += temp;
    }
    pai *= step;
    printf("PAI = %.9f\n",pai);
    gettimeofday(&end_time, 0);
    spend_time = 1000000*(end_time.tv_sec - start_time.tv_sec)+end_time.tv_usec - start_time.tv_usec;
    spend_time /=1000000;
    printf("It takes %f seconds to calculate PI.\n",spend_time);
    exit(0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值