您的位置:首页 > 编程语言

使用Perl代码获取访问网页的载入时间

2012-08-07 23:47 405 查看
接到同事的需求,说是需要做个脚本,输出访问网页的速度。考虑到也就Perl比较熟,就上网搜了搜模块。

先用的是Benchmark,大体上是先两个时间戳,然后相减:

use Benchmark;

my $timestamp1 = Benchmark->new;

#code

my $timestamp2 = Benchmark->new;

my $time_run = timediff($timestamp1 ,$timestamp2);

print timestr($time_run);

但是输出结果是以秒为单位的,显然这个是无法接受的;

然后又上网,找到一个Time::HiRes这个模块,可以支持到毫秒,网页读取就用的是LWP,代码如下:

#!perl -w

use strict;

use LWP::UserAgent;

use Time::HiRes qw (time gettimeofday tv_interval);

my $get_page = LWP::UserAgent->new;

$get_page ->timeout(100);

my $response = '';

my $webaddr = "http://www.anjuke.com";

my $t0 = [gettimeofday];

$response = $get_page ->get($webaddr);

#my $prop_detail_page = $response ->content;

my $t1 = [gettimeofday];

my $elapsed = tv_interval($t0,$t1);

print $elapsed;

大体是反应出网页读取的速度了。后面没有考虑到图片等的加载,这个需要改进一下。

大概思路是先提取网页内容,再从内容中用正则提取出各图片,然后计算图片下载所花的时间;

因为浏览器提取网页肯定是多线程,所以Perl上也要模拟多线程。

不过目前测试的结果来看,现在这个输出结果,大体上还是能够反映网速情况的~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息