sysconf(_SC_NPROCESSORS_CONF) 可以用来取得系统中CPU的个数,但无法区别超线程和双核,
在代码中可用
__asm__ __volatile__(
"xor %%eax, %%eax \n\t"
"movl $1, %%eax \n\t"
"xor %%ebx, %%ebx \n\t"
"CPUID \n\t"
"and $0x00ff0000, %%ebx \n\t"
:"=b"(temp1)
:);
ebx_count = (temp1 >> 16);
通过判断ebx_count 的值是否大于1来决定是否为超线程
另外,由于系统使用了多核处理器(smp),所以你可以将你所要运行代码强制性的绑定在某一特定的核上(并不完全肯定,因为内核自身对cpu的调度可能会改变这一绑定,所以在此只能表达为尽可能长时间的绑定在某一CPU上),具体的执行是通过一下步骤来完成,
cpu_set_t mask; //声明一个bit mask set,相当于select的fd_set
CPU_ZERO(&mask); //清零
CPU_SET(thread_num, &mask); //将对应的cpu在掩码集中设置为1
sched_setaffinity( 0, sizeof(mask), &mask );
此函数不好描述,在此引用一段原话
/* sched_setaffinity sets the CPU affinity mask of the process denoted by pid.
If pid is zero, then the current process is used.
The affinity mask is represented by the bitmask stored in mask. The least
significant bit corresponds to the first logical processor number on the
system, while the most significant bit corresponds to the last logical
processor number on the system. A set bit corresponds to a legally schedulable
CPU while an unset bit corresponds to an illegally schedulable CPU. In other
words, a process is bound to and will only run on processors whose
corresponding bit is set. Usually, all bits in the mask are set.
Also the affinity is passed on to any children! */
/* Now we have a single thread bound to each cpu on the system */
cpu_set_t mycpuid;
同样,可以通过sched_getaffinity(0, sizeof(mycpuid), &mycpuid);来取得目前cpu设置的绑定情况(亲和性设定)。
好了,以上是本人通过一些实践之后对所使用的cpu了解,希望在此能够起到抛砖引玉的作用
本人试验的平台为 IBM x346,x336系列pc server