如何在我的计算机上启用对POPCNT指令/内在函数的支持?

时间:2012-11-11 15:05:27

标签: c gcc x86 sse4 population-count

我试图在我的电脑上运行以下程序(Fedora 17 32bit)。如何使我的系统支持popcnt快速人口统计指令?

#include <stdio.h>
#include <nmmintrin.h>

int main(void)
{
    int pop = _mm_popcnt_u32(0xf0f0f0f0ULL);
    printf("pop = %d\n", pop);
    return 0;
}

我编译了程序并运行它,但得到以下异常:

[xiliu@xiliu tmp]$ gcc -Wall -march=corei7 -m32 -msse4.2 popcnt.c -o popcnt
[xiliu@xiliu tmp]$ ./popcnt 
Illegal instruction (core dumped)

以下是我的处理器的信息:

[xiliu@xiliu tmp]$ cat /proc/cpuinfo 
processor   : 0
vendor_id   : GenuineIntel
cpu family  : 6
model       : 15
model name  : Intel(R) Pentium(R) Dual  CPU  T2370  @ 1.73GHz
stepping    : 13
microcode   : 0xa4
cpu MHz     : 800.000
cache size  : 1024 KB
physical id : 0
siblings    : 2
core id     : 0
cpu cores   : 2
apicid      : 0
initial apicid  : 0
fdiv_bug    : no
hlt_bug     : no
f00f_bug    : no
coma_bug    : no
fpu     : yes
fpu_exception   : yes
cpuid level : 10
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe nx lm constant_tsc arch_perfmon pebs bts aperfmperf pni dtes64 monitor ds_cpl est tm2 ssse3 cx16 xtpr pdcm lahf_lm dtherm
bogomips    : 3458.20
clflush size    : 64
cache_alignment : 64
address sizes   : 36 bits physical, 48 bits virtual
power management:

[... repeated for 2nd core ...]

3 个答案:

答案 0 :(得分:14)

使用__builtin_popcount()代替,它不是特定于平台的。

答案 1 :(得分:11)

支持POPCNT指令的第一个CPU是Intel的Nehalem。它看起来像你的Core系列,它更老。 Hasturkun的建议适用于您的系统,但将使用多个指令而不是单个指令来实现。

如果您想要一个可移植的解决方案而不是GCC特定的解决方案,请查看Sean Eron Anderson的优秀Bit Twiddling Hacks页面,该页面具有高度优化的代码。

答案 2 :(得分:0)

您的CPU不支持POPCNT。 (见https://en.wikipedia.org/wiki/SSE4) 但是您可以使用这个免费的开源工具来检测它是否受支持: https://github.com/mgorny/cpuid2cpuflags

例如,它返回Intel Core i7-3770

CPU_FLAGS_X86: aes avx f16c mmx mmxext pclmul popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3