Memoize |
BasicWerk
EC Support
Technique
Facebook
|
20140830082259_Perl_get_http_status_template_memoize |
|
Perl_get_http_status_template_memoize
単純バージョン
#! /usr/bin/perl
use warnings;
use strict;
use LWP;
use HTTP::Status;
my $ua = LWP::UserAgent->new();
sub get_http_status {
my ($url, $ua) = @_;
return unless $url or $ua;
my $response = $ua->head($url);
my $msg = status_message($response->code);
return $msg;
}
while (my $url=<>) {
chomp $url;
my $http_status = get_http_status($url, $ua);
print "$url,$http_status\n";
}
サブルーチン化する程でもない。 URLが重複していてもリクエストしてしまう。 改善
#! /usr/bin/perl
use warnings;
use strict;
use LWP;
use HTTP::Status;
my $ua = LWP::UserAgent->new();
my %memo;
while (my $url=<>) {
chomp $url;
my $http_status = "";
if (exists $memo{$url}){
$http_status = $memo{$url};
}
else {
my $response = $ua->head($url);
$http_status = $response->code;
$memo{$url} = $http_status;
}
print "$url,$http_status\n";
}
ハッシュで Memoize するようにした。 入力はチェックしない。
# サンプルファイルは URL が 800 弱載ってる # ユニークだと 156 個の URL # 単純バージョン % time get_http_status.pl.bak imgurl.csv get_http_status.pl.bak imgurl.csv 1.10s user 0.31s system 12% cpu 11.605 total # 改善(memoize)バージョン % time get_http_status.pl imgurl.csv get_http_status.pl imgurl.csv 0.32s user 0.06s system 15% cpu 2.459 total
|
| © Shin Nakamura/BasicWerk 2014 |