1
1
#include <err.h>
2
+ #include <math.h>
2
3
#include <stdio.h>
3
4
#include <stdlib.h>
4
5
#include <sys/time.h>
@@ -13,11 +14,12 @@ double *init(int n) {
13
14
return a ;
14
15
}
15
16
16
- double * init_cont (int n , int count ) {
17
+ double * init_cont (int n , double fraction ) {
17
18
int i ;
18
19
double * a = (double * ) malloc (n * sizeof (double ));
19
20
if (a == NULL )
20
21
errx (EXIT_FAILURE , "### error: can allocate %d double array" , n );
22
+ int count = (int ) ceil (fraction * n );
21
23
for (i = 0 ; i < count ; i ++ )
22
24
a [i ] = 0.1 ;
23
25
for (i = count ; i < n ; i ++ )
@@ -30,52 +32,66 @@ long count_if(double *x, int n, int k) {
30
32
int i , j ;
31
33
for (j = 0 ; j < k ; j ++ )
32
34
for (i = 0 ; i < n ; i ++ )
33
- if (x [i ] < 0.5 )
35
+ if (x [i ] < 0.5 ) {
36
+ x [i ] = log (sqrt (x [i ]));
34
37
total ++ ;
38
+ } else
39
+ x [i ] = sqrt (- log (x [i ]));
35
40
return total ;
36
41
}
37
42
38
43
long count_cond_expr (double * x , int n , int k ) {
39
44
long total = 0 ;
40
45
int i , j ;
41
46
for (j = 0 ; j < k ; j ++ )
42
- for (i = 0 ; i < n ; i ++ )
47
+ for (i = 0 ; i < n ; i ++ ) {
43
48
total += x [i ] < 0.5 ? 1 : 0 ;
49
+ x [i ] = x [i ] < 0.5 ? log (sqrt (x [i ])) : sqrt (- log (x [i ]));
50
+ }
44
51
return total ;
45
52
}
46
53
47
54
int main (int argc , char * argv []) {
48
55
int n = 100 ;
49
56
int k = 100 ;
57
+ double fraction = 0.5 ;
50
58
double * x ;
51
59
struct timeval tv1 , tv2 ;
52
60
long counter ;
53
61
if (argc > 1 )
54
62
n = atoi (argv [1 ]);
55
63
if (argc > 2 )
56
64
k = atoi (argv [2 ]);
65
+ if (argc > 3 )
66
+ fraction = atof (argv [3 ]);
67
+ printf ("random assignment:\n" );
57
68
x = init (n );
58
69
gettimeofday (& tv1 , NULL );
59
70
counter = count_if (x , n , k );
60
71
gettimeofday (& tv2 , NULL );
61
72
printf ("if condition: %.6lf (%ld)\n" ,
62
73
tv2 .tv_sec - tv1 .tv_sec + 1.0e-6 * (tv2 .tv_usec - tv1 .tv_usec ),
63
74
counter );
75
+ free (x );
76
+ x = init (n );
64
77
gettimeofday (& tv1 , NULL );
65
78
counter = count_cond_expr (x , n , k );
66
79
gettimeofday (& tv2 , NULL );
67
80
printf ("condition expression: %.6lf (%ld)\n" ,
68
81
tv2 .tv_sec - tv1 .tv_sec + 1.0e-6 * (tv2 .tv_usec - tv1 .tv_usec ),
69
82
counter );
70
83
free (x );
71
- x = init_cont (n , counter /k );
84
+ printf ("%.3lf split:\n" , fraction );
85
+ x = init_cont (n , fraction );
72
86
gettimeofday (& tv1 , NULL );
73
87
counter = count_if (x , n , k );
74
88
gettimeofday (& tv2 , NULL );
75
89
printf ("if condition: %.6lf (%ld)\n" ,
76
90
tv2 .tv_sec - tv1 .tv_sec + 1.0e-6 * (tv2 .tv_usec - tv1 .tv_usec ),
77
91
counter );
78
92
gettimeofday (& tv1 , NULL );
93
+ free (x );
94
+ x = init_cont (n , fraction );
79
95
counter = count_cond_expr (x , n , k );
80
96
gettimeofday (& tv2 , NULL );
81
97
printf ("condition expression: %.6lf (%ld)\n" ,
0 commit comments