#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <limits.h> #include <sys/time.h>
#define NTHR 8
#define NUMNUM 8000000L
#define TNUM (NUMNUM / NTHR)
long nums[NUMNUM];
long qnums[NUMNUM];
long sortNums[NUMNUM];
pthread_barrier_t bt;
int complong(const void *arg1, const void *arg2) { long l1 = *(long *)arg1; long l2 = *(long *)arg2; if (l1 > l2) return 1; else if (l1 < l2) return -1; else return 0; }
void *thread_sort(void *arg) { long numIdx = (long)arg; qsort(&nums[numIdx], TNUM, sizeof(long), complong);
pthread_barrier_wait(&bt);
return (void *)0; }
void merge(void) { long idxs[NTHR]; int i; for (i=0; i<NTHR; i++) { idxs[i] = i * TNUM; }
int sIdx; for (sIdx=0; sIdx<NUMNUM; sIdx++) { long min = LONG_MAX; int curMinIdx = 0; for (i=0; i<NTHR; i++) { if ((idxs[i] < (i+1) * TNUM) && (nums[idxs[i]] < min)) { curMinIdx = i; min = nums[idxs[i]]; } } sortNums[sIdx] = nums[idxs[curMinIdx]]; idxs[curMinIdx]++; } }
int main(void) { unsigned long i; struct timeval start, end; long long startusec, endusec; int err; double duration;
pthread_t tid;
srandom((unsigned)time(NULL)); for (i=0; i<NUMNUM; i++) { nums[i] = rand(); qnums[i] = nums[i]; }
pthread_barrier_init(&bt, NULL, NTHR+1); gettimeofday(&start, NULL);
for (i=0; i<NTHR; i++) { err = pthread_create(&tid, NULL, thread_sort, (void *)(i * TNUM)); if (err != 0) { printf("create thread error\n"); return -1; } } pthread_barrier_wait(&bt);
merge(); gettimeofday(&end, NULL);
startusec = start.tv_sec * 1000000 + start.tv_usec; endusec = end.tv_sec * 1000000 + end.tv_usec; duration = (double)(endusec - startusec) / 1000000.0;
printf("time used for sort %d random array: %f\n", NUMNUM, duration); printf("start with: %ld, end with: %ld\n", sortNums[0], sortNums[NUMNUM-1]);
gettimeofday(&start, NULL); qsort(qnums, NUMNUM, sizeof (long), complong); gettimeofday(&end, NULL); startusec = start.tv_sec * 1000000 + start.tv_usec; endusec = end.tv_sec * 1000000 + end.tv_usec; printf("time cost using qsort: %f\n", (double)(endusec - startusec)/1000000.0); }
|