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