#!/usr/local/perl-5.8/bin/perl

use strict;
use threads;
use threads::shared;
use LWP::Simple;
use Getopt::Std;
use Time::HiRes qw(tv_interval gettimeofday);

my %opts;
getopt('cnu', \%opts);

my $total_request : shared = 0;  # $total_request は共有変数
my $success : shared = 0;        # $success は共有変数
my $failed  : shared = 0;        # $failed は共有変数

sub request
{
	my ($url) = @_;
	while($total_request < $opts{n}){
		if(get($url)){           # LWP::Simple:get でドキュメントを取得
			lock($success);      # $success をロック
			$success++;
		}else{
			lock($failed);
			$failed++;
		}
		{
			lock($total_request);
			$total_request++;
		}
		threads->yield;          # CPUを開放、他のスレッドに使わせる
	}
}

my $start_time = [gettimeofday]; # 開始時間設定
my @t;
foreach my $i(1 .. $opts{c}){    # -c で指定した数だけスレッドを起動
	$t[$i] = threads->new(\&request, $opts{u}); 
}

foreach my $i(1 .. $opts{c}){    # すべてのスレッドが終了するまで待つ
	$t[$i]->join;
}

my $end_time = tv_interval($start_time); # 実行時間を求める
my $request_per_second = sprintf("%.2f", $total_request / $end_time);

print <<END;
Concurrency Level:      $opts{c}
Time taken for tests:   $end_time seconds
Complete requests:      $success
Failed requests:        $failed
Requests per second:    $request_per_second [#/sec] (mean)
END
