1 #include <stdio.h>
2 #include <assert.h>
3 #include <sys/time.h>
4 #ifdef PTEST_USE_THREAD
5 # include <pthread.h>
6 static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
7 static pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
8 static int remaining;
9 #endif
10
11
12 extern int add1(int, int);
13
14
time_delta(struct timeval * stop,struct timeval * start)15 static double time_delta(struct timeval *stop, struct timeval *start)
16 {
17 return (stop->tv_sec - start->tv_sec) +
18 1e-6 * (stop->tv_usec - start->tv_usec);
19 }
20
measure(void)21 static double measure(void)
22 {
23 long long i, iterations;
24 int result;
25 struct timeval start, stop;
26 double elapsed;
27
28 add1(0, 0); /* prepare off-line */
29
30 i = 0;
31 iterations = 1000;
32 result = gettimeofday(&start, NULL);
33 assert(result == 0);
34
35 while (1) {
36 for (; i < iterations; i++) {
37 add1(((int)i) & 0xaaaaaa, ((int)i) & 0x555555);
38 }
39 result = gettimeofday(&stop, NULL);
40 assert(result == 0);
41
42 elapsed = time_delta(&stop, &start);
43 assert(elapsed >= 0.0);
44 if (elapsed > 2.5)
45 break;
46 iterations = iterations * 3 / 2;
47 }
48
49 return elapsed / (double)iterations;
50 }
51
start_routine(void * arg)52 static void *start_routine(void *arg)
53 {
54 double t = measure();
55 printf("time per call: %.3g\n", t);
56
57 #ifdef PTEST_USE_THREAD
58 pthread_mutex_lock(&mutex1);
59 remaining -= 1;
60 if (!remaining)
61 pthread_cond_signal(&cond1);
62 pthread_mutex_unlock(&mutex1);
63 #endif
64
65 return arg;
66 }
67
68
main(void)69 int main(void)
70 {
71 #ifndef PTEST_USE_THREAD
72 start_routine(0);
73 #else
74 pthread_t th;
75 int i, status;
76
77 add1(0, 0); /* this is the main thread */
78
79 remaining = PTEST_USE_THREAD;
80 for (i = 0; i < PTEST_USE_THREAD; i++) {
81 status = pthread_create(&th, NULL, start_routine, NULL);
82 assert(status == 0);
83 }
84 pthread_mutex_lock(&mutex1);
85 while (remaining)
86 pthread_cond_wait(&cond1, &mutex1);
87 pthread_mutex_unlock(&mutex1);
88 #endif
89 return 0;
90 }
91