#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <cmath>
#include "timer.h"
#define size 1000000
struct trick
{
int total;
char fluff[64];
};trick counters[16];
int number;
int *array;
int overall;
pthread_mutex_t lock;void fill ( )
{
srand (time (NULL));
for (int i=0; i<size; i++)
{
array[i] = rand()%10;
}
}void *countTH (void* args)
{
size_t trueid; trueid = reinterpret_cast <size_t> (args); int l_per_thread = (int)(ceil((float)size/(float)number));
int start = l_per_thread * (trueid);
int end = start + l_per_thread; if (end > size)
{
end = size;
} for (int i=start; i<end; i++)
{
if (array[i] == 3)
{
counters[trueid].total++;
}
} pthread_mutex_lock (&lock);
overall += counters[(trueid)].total;
pthread_mutex_unlock (&lock);
}void count ( )
{
for (int i=0; i<size; i++)
{
if (array[i] == 3)
{
overall++;
}
}
}
int main (int argc, char **argv)
{
int i, j, k;
pthread_t workers[16];
timer watch;
double time; array = new int[size]; time = 0.0f;
number = i = 0; for (j=0; j<10000; j++)
{
fill ();
overall = 0; watch.start ();
count (); watch.stop (); if (j > 100 && j < 9900)
{
time += watch.read ();
}
} printf ("%i\t%.3f\n", number, time/9800.0f); for (i=1; i<17; i++)
{ number = i;
time = 0.0f; for (j=0; j<10000; j++)
{ fill ();
overall = 0;
for (k=0; k<number; k++)
{
counters[k].total = 0;
} watch.start (); for (k=0; k<number; k++)
{
pthread_create (&workers[k], NULL, countTH, (void *)k);
}
for (k=0; k<number; k++)
{
pthread_join (workers[k], NULL);
} watch.stop (); if (j > 100 && j < 9900)
{
time += watch.read ();
}
}
printf ("%i\t%.3f\n", number, time/9800.0f);
} delete [] array;
}