hyperthreading code example

≡放荡痞女 提交于 2019-12-07 08:25:22

问题


Is there some sample code that exemplifies Intel's Hyperthreading performance? Is it at all accessible from user space, or does that CPU do all the work transparently for the programmer? This is for C, Linux.


回答1:


Hyperthreading performance depends on many factors and is difficult to estimate.

Just to shortly explain Hyperthreading:

  • Each core has more then one register set, but no additional execution units
  • The hyperthreads are scheduled more or less evenly

So you only really get additional performance out of hyperthreads if the two threads running on the same core use different execution units and each thread on it's own would have too many adata dependencies. For example one thread only does integer ops, the other one only floating point. Then you can see extra performance because you are using more execution units per cycle.

But this in turn depends on how your OS schedules threads onto hyperthreads. From the point of view of the OS each hyperthread is a logical CPU. So it's entirely up to the scheduler what to put there and when.

In practice hyperthreads will give you at most 10-20% extra performance. On our HPC we have turned them off (for licensing reasons mainly though).

To answer your actual question: you can not deploy code onto hyperthreads directly yourself. The OS will do that for you. You can set scheduling affinities for your userland threads, but it is still all up to the scheduler to actually deploy your threads. This is done transparently to the programmer. A good scheduler will deploy your code evenly first on cores and only resort to hyperthreads if all cores are busy.

The userland coltrol syscalls you are looking for are sched_setaffinity and pthread_setaffinity_np.

The following example code will deploy two threads on logical CPUs 0 and 1 which will correspond to the two hyperthreads on the first logical core of the first socket if hyperthreads are enabled. Still it is up to the scheduler to actually put them there. If those hyperthreads are busy then your code will sleep:

#define _GNU_SOURCE
#include <pthread.h>
#include <sched.h>
#include <stdlib.h>

void * my_thread(intptr_t cput_o_run_on) {
    cpuset_t cpuset;
    CPU_ZERO(&cpuset);
    CPU_SET(cput_o_run_on, &cpuset);

    pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset);

    // force a rescheduling
    sched_yield();

    // do something useful

    return NULL;
}

int main() {
    pthread_t thread;

    pthread_create(&thread, NULL, my_thread, 0);
    pthread_create(&thread, NULL, my_thread, 1);

    for (;;);

    return 0;
}


来源:https://stackoverflow.com/questions/18831996/hyperthreading-code-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!