- 论坛徽章:
- 0
|
Coro直接带 Coro::Semaphore; 线程池 不用自己写- use strict;
- use warnings;
- use Smart::Comments;
- use Coro;
- use Coro::LWP;
- use Coro::Semaphore;
- use LWP::UserAgent;
- use LWP::ConnCache;
- use constant LIMIT => 200;
- use Benchmark;
- my $TT0 = new Benchmark;
- my $request_times = 1000;
- print "\n Now begin testing ... \n";
- my $outpath = './data';
- my $url = 'http://www.baidu.com';
- my $semaphore = Coro::Semaphore->new(LIMIT);
- my (@coros,@error);
- my $ua = new LWP::UserAgent;
- my $conncache = new LWP::ConnCache;
- $ua->conn_cache($conncache);
- for my $num (0..999) {
- my $outfile = $outpath.'/'.$num.'.html';
- my $outfile_tmp = $outfile.'.tmp';
- push @coros, async {
- my $guard = $semaphore->guard;
-
- my $req = HTTP::Request->new(GET => $url);
- my $res = $ua->request($req);
-
- if($res->is_success){
- my $html = $res -> content;
- open(FF,">",$outfile_tmp);
- print FF $html;
- close(FF);
-
- if(-e $outfile_tmp){
- unlink $outfile;
- rename $outfile_tmp,$outfile;
- }
- print $num,'ok',$/;
- }else{
- push @error,$url;
- }
- };
- }
-
- $_ -> join for @coros;
-
- my $TT1 = new Benchmark;
- my $td = Benchmark::timediff($TT1, $TT0);
- $td = Benchmark::timestr($td);
- my ($sec) = ($td =~ /(\d+).*/);
- my $speed = sprintf("%0.1f",$request_times/$sec);
- print "\n Time expend: $td\n Average Speed: $speed Times Per Second\n\n Press Enter to close me ... \7";
复制代码 |
|