2014-10-08 45 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