Skip to content
Snippets Groups Projects

Praktikum3_13512038_13512088

Open Viktor Buntoro requested to merge vbuntoro/OpenMP:master into master
Compare and
+ 117
0
Preferences
Compare changes
omp_bucket.c 0 → 100644
+ 117
0
 
#include <stdio.h>
 
#include <stdlib.h>
 
#include <string.h>
 
#include <time.h>
 
#include <omp.h>
 
#include <assert.h>
 
#include <math.h>
 
 
int *random(int elmtNum, int* counts, int* displace, int bucketNum)
 
{
 
int *randNums = (int *)malloc(sizeof(int) * elmtNum);
 
assert(randNums != NULL);
 
int bucketSize = RAND_MAX / bucketNum;
 
int i, j;
 
int** buckets;
 
buckets = (int **)malloc(sizeof(int*) * bucketNum);
 
for(i = 0; i < bucketNum; i++)
 
{
 
buckets[i] = (int *)malloc(sizeof(int) * elmtNum);
 
counts[i] = 0;
 
displace[i] = 0;
 
}
 
for (i = 0; i < elmtNum; i++)
 
{
 
int randNum = (rand() % RAND_MAX);
 
int bucket = randNum / bucketSize;
 
buckets[bucket][counts[bucket]] = randNum;
 
counts[bucket]++;
 
for(j = bucket+1; j < bucketNum; j++)
 
{
 
displace[j]++;
 
}
 
}
 
for(i = 0; i < bucketNum; i++)
 
{
 
memcpy(randNums + displace[i], buckets[i], counts[i]);
 
free(buckets[i]);
 
}
 
free(buckets);
 
return randNums;
 
}
 
 
int countBucket(int bucket, int *array, int elmtNum, int bucketNum)
 
{
 
int bucketSize = RAND_MAX / bucketNum;
 
int i = 0;
 
int counter = 0;
 
 
for(i = 0; i < elmtNum; i++)
 
{
 
if((array[i]/bucketSize) == bucket)
 
{
 
counter++;
 
}
 
}
 
return counter;
 
}
 
 
 
void sort(int *array, int n)
 
{
 
int i, j, k;
 
for (i = 1 ; i <= n - 1; i++)
 
{
 
j = i;
 
while ( j > 0 && array[j] < array[j-1])
 
{
 
k = array[j];
 
array[j] = array[j-1];
 
array[j-1] = k;
 
j--;
 
}
 
}
 
}
 
 
int main(int argc, char** argv)
 
{
 
int* sendcounts;
 
int* displace;
 
 
if (argc != 2)
 
{
 
fprintf(stderr, "Usage: number of elements\n");
 
exit(1);
 
}
 
 
int elmtNum = atoi(argv[1]);
 
srand(time(NULL));
 
 
int threadNum = omp_get_thread_num();
 
int threadCount = omp_get_num_threads();
 
 
int *randNums = NULL;
 
sendcounts = (int *)malloc(sizeof(int)*threadCount);
 
displace = (int *)malloc(sizeof(int)*threadCount);
 
if (threadNum == 0)
 
{
 
randNums = random(elmtNum, sendcounts, displace, threadCount);
 
printf("Thread count : %d\n", threadCount);
 
}
 
printf("Thread number : %d\n", threadNum);
 
 
int *subRand = (int *)malloc(sizeof(int) * elmtNum);
 
assert(subRand != NULL);
 
#pragma omp parallel num_threads(threadCount)
 
printf("Jumlah thread : %d\n", countBucket(threadNum, subRand, elmtNum, threadCount));
 
sort(subRand, countBucket(threadNum, subRand, elmtNum, threadCount));
 
 
free(subRand);
 
 
if (threadNum == 0)
 
{
 
free(randNums);
 
}
 
free(sendcounts);
 
free(displace);
 
}