我有一個任務,我必須在Linux上用C編寫程序(我使用CentOS),它使用線程/進程來確定CPU的內核數量。 首先,我嘗試以毫秒/微秒的方式打印當前時間,因爲我知道可以運行1線程/內核(或2與HT)。但是,以毫秒爲單位,超過10個線程印刷的時間相同,而在幾微秒內則沒有一個是相同的。 其次,我試着用時鐘測量線程的執行時間,由於我有4個內核,所以同時執行4個線程的執行時間應該和執行1的時間差不多。但是我的程序中沒有一個可以讓我更接近CPU的數量。 你能幫我一些建議嗎?發現使用線程的CPU核心數量
程序打印當前時間:
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;
}
計劃測量處理時間:
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;
}
我在答案中添加了一個想法。 – Theolodis 2014-10-08 15:19:34