2015-11-02 60 views
1

我正在尝试创建一个perl脚本,用于测试一组镜像服务器以使用最佳镜像。Perl:查看下载文件需要多长时间

什么是下载文件需要多长时间的最佳方法?我试图避免系统调用像

$starttime = time(); 
    $res = `wget -o/dev/null SITE.com/file.txt`; 
    $endtime = time(); 
    $elapsed = $endtime - $starttime; 

我宁愿使用Perl函数

+0

为什么在Perl中使用它?为什么不使用shell和'time wget -o/dev/null SITE.com/file.txt'?你是否打算使用'wget'(和'system')?或者你想在Perl中重写'wget',然后呢?如果是后者,那么你需要搜索http://search.cpan.org/找到合适的模块来完成这项工作。 –

+3

@JonathanLeffler可移植性。不是每个人都有'<插入shell程序>''也不是它的相同版本。例如,OS X和Windows都不包含wget。管理Perl模块的依赖关系更容易。 – Schwern

回答

5

您可以使用LWP::SimpleHTTP::Tiny(这是自5.14.0是建于)。

use strict; 
use warnings; 
use v5.10; # for say() 

use HTTP::Tiny; 
use Time::HiRes qw(time); # to measure less than a second 
use URI; 

my $url = URI->new(shift); 
# Add the HTTP scheme if the URL is schemeless. 
$url = URI->new("http://$url") unless $url->scheme; 

my $start = time; 
my $response = HTTP::Tiny->new->get($url); 
my $total = time - $start; 

if($response->{success}) { 
    say "It took $total seconds to fetch $url"; 
    say "The content was @{[ length $response->{content} ]} bytes"; 
} 
else { 
    say "Fetching $url failed: $response->{status} $response->{reason}"; 
}