What I'm trying to do here is to compare the performance of single-threading and multi-threading by doing a simple and repetitive operation. So I have two threads assigning this random number 0xde to this array each thread taking the first and second half of the array and single-thread does the same work by itself from index 0 to the end.
What I do not understand is that even though those sub-threads are doing half the work as the single-thread(that is, the main-thread), they're taking up more time to finish their task! I don't expect it to take half the time as single-threading, but I can't possibly imagine why it would take longer than single-threading.
And even more surprisingly, If I switch the order to do the single-threading first, then I get the result I wanted. I could really use some help on this as this is all messed up in my head. Thanks in advance!
ps. I'm using a Raspberry Pi 3 which has 4 ARM processors if that helps.
This is the result I got.
Multithreading1 : 46 ms
Mulththreading2 : 50 ms
Singlethreading : 34 ms
#include <pthread.h>
#include <stdio.h>
#include <time.h>
#define SIZE 1000000
clock_t difference = 0;
clock_t difference1 = 0;
clock_t difference2 = 0;
void *substitute1(void *operand)
{
int *arr = (int *)operand;
int i=0;
clock_t before1 = clock();
for(i=0;i<(SIZE/2);i++)
{
arr[i] = 0x00de;
}
difference1 = clock() - before1;
return NULL;
}
void *substitute2(void *operand)
{
int *arr = (int *)operand;
int i=0;
clock_t before2 = clock();
for(i=(SIZE/2);i<SIZE;i++)
{
arr[i] = 0x00de;
}
difference2 = clock() - before2;
return NULL;
}
void single_thread(int *arr);
int main(void)
{
int arr[SIZE];
int test[SIZE];
int msec1, msec2;
// declare thread variables
pthread_t thread1;
pthread_t thread2;
// create threads
pthread_create(&thread1, NULL, substitute1, arr);
pthread_create(&thread2, NULL, substitute2, arr);
// wait untill the two threads do all their work
while(arr[SIZE/2 - 1] != 0x00de) {/*printf("arr[%d] = %x\n", SIZE/2 - 1, arr[SIZE/2 -1]);*/};
while(arr[SIZE-1] != 0x00de) {/*printf("arr[%d] = %x\n", SIZE-1, arr[SIZE-1]);*/};
// and then join
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// convert clocks to milliseconds
msec1 = difference1 * 1000 / CLOCKS_PER_SEC;
msec2 = difference2 * 1000 / CLOCKS_PER_SEC;
printf("Multithreading1 : %d ms\n", msec1);
printf("Mulththreading2 : %d ms\n", msec2);
// here's the single-threading
single_thread(test);
return 0;
}
void single_thread(int *arr)
{
int msec = 0, i = 0;
// declare initial clock
clock_t single_before = clock();
for(i=0;i<SIZE;i++)
{
arr[i] = 0x00de;
}
difference = clock() - single_before;
// convert clocks to milliseconds
msec = difference * 1000 / CLOCKS_PER_SEC;
printf("Singlethreading : %d ms\n", msec);
}