双线程计算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);
}