/
pisum.c
50 lines (35 loc) · 992 Bytes
/
pisum.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdint.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define BILLION 1000000000L
int main(int argc, char** argv){
/* https://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/gettime.html */
double volatile s = 0.;
int N = 1000000;
if (argc>1) {
N = atoi(argv[1]);
}
printf("--> C. N=%d \n", N);
struct timespec start, end;
#if (!defined(__APPLE__))
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
for (int k=1; k<=N; k++) {
s += pow(-1., k+1.) / (2.*k-1);
}
#if (!defined(__APPLE__))
clock_gettime(CLOCK_MONOTONIC, &end);
#endif
uint64_t diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
s = 4*s;
if (fabs(s-M_PI)>1e-4) {
fprintf(stderr,"C pisum: large error magnitude");
return EXIT_FAILURE;
}
#if (!defined(__APPLE__))
printf("%.3e seconds \n",(float) diff/BILLION);
#endif
return EXIT_SUCCESS;
}