Booster Угу, с таблицей на 256 байт слишком много операций получается, а вот с таблицей на 65536 по скорости почти сравнимо с кодом из 56 сообщения.
Шутишь? Код (Text): #include <iostream> #include <algorithm> unsigned int popcount(unsigned int v); unsigned int bitcount(unsigned int n); int bits_in_16bits[0x10000]; int test1(int a[], int size); int test2(int a[], int size); unsigned int bitcountFast (unsigned int n); int main (int argc, char* argv[]) { for (int i=0; i<0x10000; i++) { bits_in_16bits[i] = bitcount(i); } int n = 0x100000; int array[n]; for (int i=0; i<n; i++) { array[i] = std::rand(); } int res2 = test2(array, n); int res1 = test1(array, n); std::cout<<res1<<" "<<res2<<std::endl; } int test1(int a[], int size) { int res = 0; for (int c=0; c<100; c++) { for (int i=0; i<size; i++) { res += popcount(a[i]); } } return res; } int test2(int a[], int size) { int res = 0; for (int c=0; c<100; c++) { for (int i=0; i<size; i++) { res += bitcountFast(a[i]); } } return res; } unsigned int popcount(unsigned int v) { unsigned int retVal; __asm ( ".intel_syntax noprefix\n" "MOV EAX,%0 \n" "MOV EDX,EAX \n" "SHR EAX,1 \n" "AND EAX,0x055555555 \n" "SUB EDX,EAX \n" "MOV EAX,EDX \n" "SHR EDX,2 \n" "AND EAX,0x033333333 \n" "AND EDX,0x033333333 \n" "ADD EAX,EDX \n" "MOV EDX,EAX \n" "SHR EAX,4 \n" "ADD EAX,EDX \n" "AND EAX,0x00F0F0F0F \n" "IMUL EAX,0x001010101 \n" "SHR EAX,24 \n" "MOV %1,EAX" :"=r"(retVal) :"r"(v) ); return retVal; } unsigned int bitcount(unsigned int n) { /* works for 32-bit numbers only */ /* fix last line for 64-bit numbers */ register unsigned int tmp; tmp = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111); return ((tmp + (tmp >> 3)) & 030707070707) % 63; } unsigned int bitcountFast (unsigned int n) { // works only for 32-bit ints // return bits_in_16bits [n & 0xffff] + bits_in_16bits [(n >> 16) & 0xffff] ; } Код (Text): Flat profile: Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls s/call s/call name 48.10 2.14 2.14 104857600 0.00 0.00 popcount(unsigned int) 28.61 3.41 1.27 104857600 0.00 0.00 bitcountFast(unsigned int)