in reply to Re: how to quickly tell if number is in an array
in thread how to quickly tell if number is in an array
If his quickly means faster, let's compare those two solutions:
use Benchmark qw(timethese); use strict; use warnings; my @array = (1 .. 100000); timethese(100, {granfather => \&grandfather, usual => \&usual}); sub grandfather { return 1 if grep {$_ == 100000} @array; } sub usual { for my $a (@array) { return 1 if ($a == 100000); } return 0; }
If the element we serach is at the end, grandfather's is a little bit faster:
Benchmark: timing 100 iterations of granfather, usual... granfather: 4 wallclock secs ( 3.58 usr + 0.00 sys = 3.58 CPU) @ 27 +.95/s (n=1 00) usual: 4 wallclock secs ( 4.13 usr + 0.00 sys = 4.13 CPU) @ 24 +.24/s (n=1 00)
But if you change the above code to search for 3 (at the beginning of the array), then the usual way is much faster:
Benchmark: timing 100 iterations of granfather, usual... granfather: 3 wallclock secs ( 3.58 usr + 0.00 sys = 3.58 CPU) @ 27 +.95/s (n=1 00) usual: 0 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU) (warning: too few iterations for a reliable count)
With something in the middle say 50000, the usual way is still close to 50% faster.
Benchmark: timing 100 iterations of granfather, usual... granfather: 4 wallclock secs ( 3.69 usr + 0.03 sys = 3.72 CPU) @ 26 +.89/s (n=1 00) usual: 2 wallclock secs ( 2.08 usr + 0.00 sys = 2.08 CPU) @ 48 +.12/s (n=1 00)
Now you know which direction it is pointing to ;-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: how to quickly tell if number is in an array
by GrandFather (Saint) on Oct 12, 2005 at 01:27 UTC | |
by sauoq (Abbot) on Oct 12, 2005 at 02:15 UTC |