Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdio>
- #include <cstdlib>
- #include <ctime>
- const int n = 10000000;
- typedef long long ll;
- const int PLEN = 16;
- const int PLEN2 = PLEN * 2;
- const int PLEN3 = PLEN * 3;
- int cnt[1 << PLEN];
- int countPrecalc(ll x) {
- return cnt[x & 0xFFFF] + cnt[(x >> PLEN) & 0xFFFF] + cnt[(x >> PLEN2) & 0xFFFF] + cnt[(x >> PLEN3) & 0xFFFF];
- }
- int countLoglog(ll x) {
- x = (x & 0x5555555555555555ll) + ((x & 0xAAAAAAAAAAAAAAAAll) >> 1);
- x = (x & 0x3333333333333333ll) + ((x & 0xCCCCCCCCCCCCCCCCll) >> 2);
- x = (x & 0x0F0F0F0F0F0F0F0Fll) + ((x & 0xF0F0F0F0F0F0F0F0ll) >> 4);
- x = (x & 0x00FF00FF00FF00FFll) + ((x & 0xFF00FF00FF00FF00ll) >> 8);
- x = (x & 0x0000FFFF0000FFFFll) + ((x & 0xFFFF0000FFFF0000ll) >> 16);
- x = (x & 0x00000000FFFFFFFFll) + ((x & 0xFFFFFFFF00000000ll) >> 32);
- return x;
- }
- int countSimple(ll x) {
- int a = 0;
- for (; x; x >>= 1) a += x & 1;
- return a;
- }
- ll data[n];
- int main() {
- cnt[0] = 0;
- for (int i = 1; i < (1 << PLEN); i++)
- cnt[i] = cnt[i & (i - 1)] + 1;
- printf("Filling in... ");
- for (int i = 0; i < n; i++) data[i] = ((ll)rand() << 48) | ((ll)rand() << 32) | ((ll)rand() << 16) | (ll)rand();
- printf("OK\n");
- time_t stime; int sum;
- printf("Counting with __builtin_popcount... ");
- stime = clock();
- sum = 0;
- for (int i = 0; i < n; i++) sum += __builtin_popcountll(data[i]);
- printf("OK, sum=%d, time=%.3lf\n", sum, (double)(clock() - stime) / CLOCKS_PER_SEC);
- printf("Counting with countPrecalc... ");
- stime = clock();
- sum = 0;
- for (int i = 0; i < n; i++) sum += countPrecalc(data[i]);
- printf("OK, sum=%d, time=%.3lf\n", sum, (double)(clock() - stime) / CLOCKS_PER_SEC);
- printf("Counting with countLoglog... ");
- stime = clock();
- sum = 0;
- for (int i = 0; i < n; i++) sum += countLoglog(data[i]);
- printf("OK, sum=%d, time=%.3lf\n", sum, (double)(clock() - stime) / CLOCKS_PER_SEC);
- printf("Counting with countSimple... ");
- stime = clock();
- sum = 0;
- for (int i = 0; i < n; i++) sum += countSimple(data[i]);
- printf("OK, sum=%d, time=%.3lf\n", sum, (double)(clock() - stime) / CLOCKS_PER_SEC);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement