@techno_neko
組み込み系
Hokkaido.pm
# スライドの都合上、データ数は2のn乗 my $cnt = 0x10000; my @data = map $_ * 5, 1..$cnt;
sub grep_search { my $th = shift; my @tmp = grep { $th < $data[$_] } 0..(scalar(@data) - 1); return ( shift @tmp ); }
my @data = ( 5, 10, 15, 20, 25, 30, 35, 40 ); my $i = scalar(@data) - 1; # 探索結果(仮)
sub binary_search { my $th = shift; my $i = scalar(@data) - 1; my $step = $i; while ( 0 < ($step /= 2) ) { $i -= $step if $th < $data[$i-$step]; } return $i; }
use v5.10;
use strict;
use warnings;
use Time::HiRes qw/time/;
# スライドの都合上、データ数は2のn乗
my $cnt = 0x10000;
my @data = map $_ * 5, 1..$cnt;
sub binary_search {
my $th = shift;
my $i = scalar(@data) - 1;
my $step = $i;
while ( 0 < ($step /= 2) ) {
$i -= $step if $th < $data[$i-$step];
}
return $i;
}
sub grep_search {
my $th = shift;
my @tmp = grep {
$th < $data[$_]
} 0..(scalar(@data) - 1);
return ( shift @tmp );
}
#
# 確実に存在するデータを入力して、
# その値が存在する要素の添字を得る
#
my $th = 10000;
say 'scalar(@data) = ', scalar(@data);
say '$th = ', $th;
{
my $start = time();
my $index = binary_search( $th );
say '$index = ', $index, ', $data[$index] = ', $data[$index];
say time() - $start;
}
{
my $start = time();
my $index = grep_search( $th );
say '$index = ', $index, ', $data[$index] = ', $data[$index];
say time() - $start;
}
$ perl aaa.pl scalar(@data) = 65536 $th = 10000 $index = 2000, $data[$index] = 10005 0.000295877456665039 $index = 2000, $data[$index] = 10005 0.0136890411376953
Perlのバージョンは5.18.1
CPU 1.8 GHz Intel Core i5
メモリ 4GB
/
#