Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^2: How to do popcount (aka Hamming weight) in Perl

by marioroy (Prior)
on Sep 27, 2017 at 07:13 UTC ( [id://1200171]=note: print w/replies, xml ) Need Help??


in reply to Re: How to do popcount (aka Hamming weight) in Perl
in thread How to do popcount (aka Hamming weight) in Perl

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1200171]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2024-03-29 09:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found