If needed, Inline C code supporting 64 and 32 bits.

use strict; use warnings; use Inline 'C' => Config => BUILD_NOISY => 1, CLEAN_AFTER_BUILD => 0; use Inline 'C' => <<'END_C'; #include <stdint.h> unsigned popcnt2( SV *sv ) { unsigned count = 0; #ifdef __LP64__ static const uint64_t m1 = UINT64_C(0x5555555555555555); static const uint64_t m2 = UINT64_C(0x3333333333333333); static const uint64_t m4 = UINT64_C(0x0f0f0f0f0f0f0f0f); static const uint64_t h01 = UINT64_C(0x0101010101010101); uint64_t x = (uint64_t) SvUVX( sv ); x = x - ((x >> 1) & m1); x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; count += (unsigned) ((x * h01) >> 56); #else static const uint32_t m1 = UINT32_C(0x55555555); static const uint32_t m2 = UINT32_C(0x33333333); static const uint32_t m4 = UINT32_C(0x0f0f0f0f); static const uint32_t h01 = UINT32_C(0x01010101); uint32_t x = (uint32_t) SvUVX( sv ); x = x - ((x >> 1) & m1); x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; count += (unsigned) ((x * h01) >> 24); #endif return count; } END_C use Benchmark qw( cmpthese ); my $start = 2 ** 32 - 42; my $end = $start + 1000000; cmpthese -3, { Six2 => sub { popcnt2($_) for $start .. $end }, };

Regards, Mario


In reply to Re^2: How to do popcount (aka Hamming weight) in Perl by marioroy
in thread How to do popcount (aka Hamming weight) in Perl (popcount References) by eyepopslikeamosquito

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.