首页 文章

使用线程发现CPU核心数

提问于
浏览
0

我有一个任务,我必须在Linux上编写一个C程序(我使用CentOS),它使用线程/进程来确定CPU的内核数量 . 首先,我尝试以毫微微/微秒的速度打印当前时间,因为我知道可以运行1thread / core(或者带有HT的2) . 但是通过毫秒,超过10个线程打印相同的时间和微秒没有一个是相同的 . 其次我尝试用时钟测量线程的执行时间,假设我有4个内核,同时4个线程的执行时间应该几乎和执行1一样长 . 但是我的程序都不能让我更接近数字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;
}

2 回答

  • 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
    

    你当然可以调整你开始的线程数量,以及你让他们睡觉的时间,但我想如果你只睡了一毫秒,你可能会因为上下文切换和后台任务而得到不具代表性的时间 .


    而不是在线程中睡觉做类似的事情:

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

    你执行它一次而不启动一个线程,什么会占用时间 x . 那个时间将是参考时间 .

    如果通过添加越来越多的 pthready ),执行相同的功能,你不会消耗比 x 更多的时间,那么你知道你最有可能至少拥有 y 核心 . 在某些时候,使用 z 个线程,时间将在 2x 左右,此时你就会知道你有 z-1 个核心 .

  • 1
    #include <unistd.h>
    
    int number_of_cores = sysconf(_SC_NPROCESSORS_ONLN);
    

    这不是便携式的,仅适用于Linux afaik .

相关问题