in reply to Re: Anyone use "xor" in conditionals?
in thread Anyone use "xor" in conditionals?
sub is_leap { my $year = shift; return 0 if $year % 4; return 1 if $year % 100; !($year % 400) }
That code does one modulus operation in 75% of the cases, two modules operations in 24% of the cases, and only in 1% of the cases, it does 3 modulus operations.
A benchmark shows the expected results. The code that always does three modulus operations is the slowest - the code that on averages does the least modulus operations is the fastest.
#!/usr/bin/perl use strict; use warnings; use Benchmark qw /cmpthese/; sub isleap { my ($year) = @_; return 1 if (( $year % 400 ) == 0 ); # 400's are leap return 0 if (( $year % 100 ) == 0 ); # Other centuries are not return 1 if (( $year % 4 ) == 0 ); # All other 4's are leap return 0; # Everything else is not } sub browseruk { my ($year) = @_; not $year % 4 xor $year % 100 xor $year % 400; } sub abigail { my ($year) = @_; return 0 if $year % 4; return 1 if $year % 100; !($year % 400) } cmpthese -10 => { isleap => 'my $v = isleap $_ for 1800 .. 2199', browseruk => 'my $v = browseruk $_ for 1800 .. 2199', abigail => 'my $v = abigail $_ for 1800 .. 2199', }; __END__ Benchmark: running abigail, browseruk, isleap, each for at least 10 CP +U seconds... abigail: 11 wallclock secs (10.90 usr + 0.00 sys = 10.90 CPU) @ 18 +43.58/s (n=20095) browseruk: 10 wallclock secs (10.48 usr + 0.01 sys = 10.49 CPU) @ 14 +09.82/s (n=14789) isleap: 11 wallclock secs (10.76 usr + 0.01 sys = 10.77 CPU) @ 14 +54.04/s (n=15660) Rate browseruk isleap abigail browseruk 1410/s -- -3% -24% isleap 1454/s 3% -- -21% abigail 1844/s 31% 27% --
Abigail
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Anyone use "xor" in conditionals?
by BrowserUk (Patriarch) on Jul 15, 2003 at 01:15 UTC | |
by dragonchild (Archbishop) on Jul 15, 2003 at 02:17 UTC | |
by BrowserUk (Patriarch) on Jul 15, 2003 at 02:30 UTC | |
by zengargoyle (Deacon) on Jul 15, 2003 at 03:36 UTC | |
by dragonchild (Archbishop) on Jul 15, 2003 at 13:49 UTC | |
| |
by Abigail-II (Bishop) on Jul 15, 2003 at 07:05 UTC | |
by BrowserUk (Patriarch) on Jul 15, 2003 at 09:31 UTC |