Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: How can I tell if a number is a power of 2?

by larryk (Friar)
on Jan 28, 2002 at 22:31 UTC ( #142140=note: print w/ replies, xml ) Need Help??


in reply to How can I tell if a number is a power of 2?

After a session in the CB:

#!perl use strict; use warnings; use Benchmark qw/cmpthese/; sub one { my $number = shift; sprintf('%b',$number) =~ /^10*$/ ? 1 : 0; } sub two { my $number = shift; 1 == reverse sprintf('%b',$number) ? 1 : 0; } sub three { my $number = shift; 1 == substr(sprintf('%b',$number),0,1) ? 1 : 0; } my %h = map { $_ ** 2 => 1 } (0..63); sub jeffa { my $number = shift; exists $h{$number} ? 1 : 0; } sub tye { my $x = shift; 0 == ( $x & ($x-1) ) ? 1 : 0; } my %h2 = (); @h2{map $_**2,0..63}; # word of mouth: by tilly sub tilly { # really just another impl. of jeffa's lookup my $number = shift; exists $h2{$number} ? 1 : 0; } cmpthese( -5, { one => q!one(rand 1000000)!, two => q!two(rand 1000000)!, three => q!three(rand 1000000)!, tye => q!tye(rand 1000000)!, jeffa => q!jeffa(rand 1000000)!, tilly => q!tilly(rand 1000000)!, } ); __END__ Benchmark: running jeffa, one, three, tilly, two, tye, each for at lea +st 5 CPU seconds... jeffa: 6 wallclock secs ( 5.01 usr + 0.00 sys = 5.01 CPU) @ 62 +422.92/s (n=312614) one: 5 wallclock secs ( 5.14 usr + 0.00 sys = 5.14 CPU) @ 11 +9667.70/s (n=614733) three: 5 wallclock secs ( 5.25 usr + 0.00 sys = 5.25 CPU) @ 90 +412.81/s (n=474396) tilly: 6 wallclock secs ( 5.01 usr + 0.00 sys = 5.01 CPU) @ 63 +202.16/s (n=316390) two: 6 wallclock secs ( 5.14 usr + 0.00 sys = 5.14 CPU) @ 11 +9035.80/s (n=611725) tye: 6 wallclock secs ( 5.25 usr + 0.00 sys = 5.25 CPU) @ 21 +0491.04/s (n=1104657) Rate jeffa tilly three two one tye jeffa 62423/s -- -1% -31% -48% -48% -70% tilly 63202/s 1% -- -30% -47% -47% -70% three 90413/s 45% 43% -- -24% -24% -57% two 119036/s 91% 88% 32% -- -1% -43% one 119668/s 92% 89% 32% 1% -- -43% tye 210491/s 237% 233% 133% 77% 76% --


Comment on Re: How can I tell if a number is a power of 2?
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (10)
As of 2014-08-29 22:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (289 votes), past polls