I have an assignment in which i have to write a program in C on Linux(i use CentOS), which uses threads/processes to determine the number of cores from the CPU. Firstly I tried to print the current time in mili/microseconds, because I know that there can run 1thread/core(or 2 with HT). But by miliseconds more than 10 threads printed the same amount of time and by microseconds none were identical. Secondly I tried to measure the execution time of threads with clock, given I have 4 cores, the execution time of 4 threads at the same time should take almost as long as executing 1.But none of my programs could bring me closer to the number of CPU's. Could you help me with some suggestions please?
Program printing current time:
pthread_t th[N];
void* afis ()
{
//time_t now;
//time(&now);
//printf("%s", ctime(&now));
struct timeval start, end;
long mtime, seconds, useconds;
gettimeofday(&start, NULL);
// usleep(2000);
gettimeofday(&end, NULL);
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
mtime = seconds + useconds;
printf("Thread with TID:%d Elapsed time: %ld microsecons\n",(unsigned int)pthread_self(), mtime);
}
int main()
{
int i;
for (i=0;i<N;i++)
{
pthread_create(&th[i],NULL,afis,NULL);
}
for(i=0;i<N;i++)
{
pthread_join(th[i],NULL);
}
return 0;
}
Program measuring processing time:
pthread_t th[N];
void* func(void* arg)
{
int x;
int k;
int n=(int)arg;
for(k=0;k<10000000;k+=n)
{
x=0;
}
}
int main()
{
int i,j;
for (i=0;i<N;i++)
{
clock_t start, end, total;
start=clock();
for(j=0;j<i;j++)
{
printf("execution nr: %d\n",i);
pthread_create(&th[j],NULL,func,(int*)i);
}
for(j=0;j<i;j++)
{
pthread_join(th[j],NULL);
}
end=clock();
printf("start = %ld, end = %ld\n", start, end);
total=((double)(end-start) )/ CLOCKS_PER_SEC;
printf("total=%ld\n",total);
}
return 0;
}