Today I had an issue calculating prime numbers with threads in python. It was nearly as slow as without a thread(See Question).
Now I created the same code thinking the python problem would not exist there in C using pthread.
#include <stdio.h>
#include <time.h>
#include <pthread.h>
int isPrime(int number) {
int i;
for (i=2; i<number; i++) {
if (number % i == 0 && i != number) return 0;
}
return 1;
}
void calcPrimeNumbersFromNtoM(int n, int m){
for (int i = n; i <= m; i++) {
if (isPrime(i)) {
//printf("%i\n",i);
}
}
}
void *calcFirstHalf(){
calcPrimeNumbersFromNtoM(1,5000);
return NULL;
}
void *calcSecondHalf(){
calcPrimeNumbersFromNtoM(5001,10000);
return NULL;
}
void calcThreadedPrimenumbers(){
pthread_t t1, t2;
pthread_create(&t1, NULL, calcFirstHalf, NULL);
pthread_create(&t2, NULL, calcSecondHalf, NULL);
//wait for the threads to finish
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
int main(int argc, const char * argv[])
{
clock_t startNT, endNT,startT, endT;
double cpu_time_usedNT,cpu_time_usedT;
startNT = clock();
calcPrimeNumbersFromNtoM(1, 10000);
endNT = clock();
cpu_time_usedNT = ((double) (endNT - startNT)) / CLOCKS_PER_SEC;
startT = clock();
calcThreadedPrimenumbers();
endT = clock();
cpu_time_usedT = ((double) (endT - startT)) / CLOCKS_PER_SEC;
printf("--------Results-----------\n");
printf("Non threaded took: %f secs\n",cpu_time_usedNT);
printf("Threaded took: %f secs\n",cpu_time_usedT);
return 0;
}
The result is that threading is again as slow as non threaded:
--------Results-----------
Non threaded took: 0.020624 secs
Threaded took: 0.027257 secs
This is confusing me a lot. Is there something wrong with my code? Is it true that threads are not necessary faster than using no thread? If yes what is the explanation for this?
Is this caused by the OS needing to schedule the same task only divided in two parts which leads to the same amount of time?
Maybe it is important: I use an 2.6Ghz Core i5 MacBook with OSX 10.9