in reply to Testing a number for oddness

Update: chipmunk notes that I was using % 1 instead of % 2, which was a stupid mistake on my part. I've updated the code and benchmarks, but the results do not differ significantly.

Because I'm bored and in love with Inline:

use Benchmark 'timethese'; use Inline C => <<'EoF'; int c_and(int num) { return(num & 1); } int c_mod(int num) { return(num % 2); } EoF my $num = 5; sub perl_mod { $_[0] % 2 } sub perl_and { $_[0] & 1 } timethese(10_000_000, { perl_mod => sub { perl_mod($num) }, perl_and => sub { perl_and($num) }, c_mod => sub { c_mod($num) }, c_and => sub { c_and($num) }, }); __END__ c_and: 7 wallclock secs ( 7.09 usr + 0.05 sys = 7.14 CPU) @ 14 +00560.22/s (n=10000000) c_mod: 8 wallclock secs ( 7.44 usr + -0.01 sys = 7.43 CPU) @ 13 +45895.02/s (n=10000000) perl_and: 17 wallclock secs (16.63 usr + -0.01 sys = 16.62 CPU) @ 60 +1684.72/s (n=10000000) perl_mod: 16 wallclock secs (16.65 usr + 0.01 sys = 16.66 CPU) @ 60 +0240.10/s (n=10000000)
For all intents and purposes, it seems like both methods are equally fast, at least as far as any Perl implementation is concerned, and at least on my architecture (i686-linux, P3/850). A few microseconds isn't going to make a difference in any real-world application, and Perl itself may have quirks that cause one implementation to be slower or faster than another. It may very well be that a 100% C solution to all of this will show the expected results (with & being marginally faster), but it doesn't look like you're going to get those results in Perl.

Additionally, you guys are relying on Benchmark results with way too few iterations. If you're wanting to compare and contrast algorithms and are getting Benchmark results in the 0-2 second range, you need to increase your repetitions at least an order of magnitude.