#!/usr/bin/env perl use strict; use warnings; use Benchmark qw{cmpthese}; my $x = 1 << 0; my $y = 1 << 1 ^ 1 << 4 ^ 1 << 7 ^ 1 << 15 ^ 1 << 31 ^ 1 << 63; my @test_results = ( hd_OP($x, $y), hd_Ken($x, $y), hd_OP($x, $y, 16), hd_Ken($x, $y, 16), hd_OP($x, $y, 32), hd_Ken($x, $y, 32), hd_OP($x, $y, 64), hd_Ken($x, $y, 64), ); print "Test results: @test_results\n"; cmpthese(-1, { hd_OP_8 => sub { hd_OP($x, $y) }, hd_Ken_8 => sub { hd_Ken($x, $y) }, }); cmpthese(-1, { hd_OP_16 => sub { hd_OP($x, $y, 16) }, hd_Ken_16 => sub { hd_Ken($x, $y, 16) }, }); cmpthese(-1, { hd_OP_32 => sub { hd_OP($x, $y, 32) }, hd_Ken_32 => sub { hd_Ken($x, $y, 32) }, }); cmpthese(-1, { hd_OP_64 => sub { hd_OP($x, $y, 64) }, hd_Ken_64 => sub { hd_Ken($x, $y, 64) }, }); sub hd_Ken { my ($diff, $bits, $count, $mask) = ($_[0] ^ $_[1], $_[2] || 8, 0); $mask = 1 << $_, $diff & $mask && ++$count for 0 .. $bits - 1; $count; } sub hd_OP { my ($d1,$d2,$bits) = @_; $bits ||= 8; my $diff = $d1 ^ $d2; my $count = 0; for my $b ( 0 .. $bits-1 ) { my $mask = 1 << $b; ++ $count if $diff & $mask } return $count }