2014-10-08 57 views
0

我有一個任務,我必須在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; 
} 
+0

我在答案中添加了一個想法。 – Theolodis 2014-10-08 15:19:34

回答

4

什麼你應該做的是(僞代碼):

get the actual time (start time) 
start 40 threads 
    each busy for one second; 
wait for all of them to stop 
get the actual time (stop time) 

如果你分析它花了40個線程執行的時間,你會知道的核心數量,或在至少你可以做一個假設:

if the time was around 40s: you have one core 
else if the time was around 20s: you have two 
and so on 

你當然可以適應啓動的線程數目,藏漢作爲的時候,你讓他們睡覺,但我想,如果你睡了一毫秒只有你可以得到次由於c而不具代表性ontext開關和後臺任務。


而是在休眠線程的執行類似:

highlyCpuIntensiveTask() 
{ 
    //calculate something that takes up the time x (best would be above 1 second) 
} 

你一旦執行它,而無需啓動一個線程,你會佔用時間x。那個時間將是參考時間。

如果增加更多pthread S(y),執行同樣的功能,你不使用了相當多的時間比x,那麼你知道你這樣做很可能至少有y核心。在某些時候,z線程的時間將在2x左右,此時您將知道您擁有z-1核心。

+1

好的解決方案! :) – dom0 2014-10-08 13:37:08

+0

以及如何等待所有線程完成?如果我使用互斥鎖,那麼只有1個線程將能夠一次訪問該功能,並且對於4個內核,它應該可以用於4個線程立即訪問它 – balinteu 2014-10-08 14:51:32

+1

?無論您啓動多少個線程,即使在單核系統上,我都希望花費大約1秒的時間。 – 2014-10-08 15:01:56

1
#include <unistd.h> 

int number_of_cores = sysconf(_SC_NPROCESSORS_ONLN); 

這是不可移植的,僅適用於Linux的AFAIK。

+0

感謝您的幫助,但問題是我不允許以任何形式詢問處理器,我需要使用線程/進程來確定它 – balinteu 2014-10-08 13:34:15