Hakmem: classic programming hacks
inwap.com
inwap.com
Bit Twiddling Hacks - http://graphics.stanford.edu/~seander/bithacks.html
The book Hacker's Delight by Henry S. Warren Jr and published by Addison Wesley - homepage at http://www.hackersdelight.org/
static inline int array_non_zero_count_mmx( int16_t *v )
{
int count;
asm(
"pxor %%mm7, %%mm7 \n"
"movq (%1), %%mm0 \n"
"movq 8(%1), %%mm1 \n"
"packsswb 16(%1), %%mm0 \n"
"packsswb 24(%1), %%mm1 \n"
"pcmpeqb %%mm7, %%mm0 \n"
"pcmpeqb %%mm7, %%mm1 \n"
"paddb %%mm0, %%mm1 \n"
"psadbw %%mm7, %%mm1 \n"
"movd %%mm1, %0 \n"
:"=r"(count)
:"r"(v)
);
return (count+0x10)&0xff;
}
It is, not surprisingly, an order of magnitude faster than the C equivalent. Bonus points for understanding what the "0x10" is for at the end.