Advertisement
Guest User

Popcount speed test

a guest
Oct 16th, 2010
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.12 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <ctime>
  4.  
  5. const int n = 10000000;
  6. typedef long long ll;
  7.  
  8. const int PLEN = 16;
  9. const int PLEN2 = PLEN * 2;
  10. const int PLEN3 = PLEN * 3;
  11.  
  12. int cnt[1 << PLEN];
  13. int countPrecalc(ll x) {
  14.   return cnt[x & 0xFFFF] + cnt[(x >> PLEN) & 0xFFFF] + cnt[(x >> PLEN2) & 0xFFFF] + cnt[(x >> PLEN3) & 0xFFFF];
  15. }
  16.  
  17. int countLoglog(ll x) {
  18.   x = (x & 0x5555555555555555ll) + ((x & 0xAAAAAAAAAAAAAAAAll) >> 1);
  19.   x = (x & 0x3333333333333333ll) + ((x & 0xCCCCCCCCCCCCCCCCll) >> 2);
  20.   x = (x & 0x0F0F0F0F0F0F0F0Fll) + ((x & 0xF0F0F0F0F0F0F0F0ll) >> 4);
  21.   x = (x & 0x00FF00FF00FF00FFll) + ((x & 0xFF00FF00FF00FF00ll) >> 8);
  22.   x = (x & 0x0000FFFF0000FFFFll) + ((x & 0xFFFF0000FFFF0000ll) >> 16);
  23.   x = (x & 0x00000000FFFFFFFFll) + ((x & 0xFFFFFFFF00000000ll) >> 32);
  24.   return x;
  25. }
  26.  
  27. int countSimple(ll x) {
  28.   int a = 0;
  29.   for (; x; x >>= 1) a += x & 1;
  30.   return a;
  31. }
  32.  
  33. ll data[n];
  34. int main() {
  35.   cnt[0] = 0;
  36.   for (int i = 1; i < (1 << PLEN); i++)
  37.     cnt[i] = cnt[i & (i - 1)] + 1;
  38.  
  39.   printf("Filling in... ");
  40.   for (int i = 0; i < n; i++) data[i] = ((ll)rand() << 48) | ((ll)rand() << 32) | ((ll)rand() << 16) | (ll)rand();
  41.   printf("OK\n");
  42.  
  43.   time_t stime; int sum;
  44.  
  45.   printf("Counting with __builtin_popcount... ");
  46.   stime = clock();
  47.   sum = 0;
  48.   for (int i = 0; i < n; i++) sum += __builtin_popcountll(data[i]);
  49.   printf("OK, sum=%d, time=%.3lf\n", sum, (double)(clock() - stime) / CLOCKS_PER_SEC);
  50.  
  51.   printf("Counting with countPrecalc... ");
  52.   stime = clock();
  53.   sum = 0;
  54.   for (int i = 0; i < n; i++) sum += countPrecalc(data[i]);
  55.   printf("OK, sum=%d, time=%.3lf\n", sum, (double)(clock() - stime) / CLOCKS_PER_SEC);
  56.  
  57.   printf("Counting with countLoglog... ");
  58.   stime = clock();
  59.   sum = 0;
  60.   for (int i = 0; i < n; i++) sum += countLoglog(data[i]);
  61.   printf("OK, sum=%d, time=%.3lf\n", sum, (double)(clock() - stime) / CLOCKS_PER_SEC);
  62.  
  63.   printf("Counting with countSimple... ");
  64.   stime = clock();
  65.   sum = 0;
  66.   for (int i = 0; i < n; i++) sum += countSimple(data[i]);
  67.   printf("OK, sum=%d, time=%.3lf\n", sum, (double)(clock() - stime) / CLOCKS_PER_SEC);
  68.  
  69.   return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement