028c6b60b63d74283afb88cfc310553863283f69
[lab.git] / misc / httpbench.pl
1 #! /usr/bin/perl -w
2
3 use strict;
4 use warnings;
5 use utf8;
6
7 use Getopt::Long;
8 use Parallel::ForkManager;
9 use LWP::Simple;
10 use Time::HiRes qw(sleep);
11
12 GetOptions(
13     'h|help'            => \ my $help,
14     'i|inputfile=s'     => \ my $file,
15     'c|concurrency=i'   => \ my $concurrency,
16     'n|loops=i'         => \ my $loops,
17     'w|wait=f'          => \ my $wait,
18 ) or usage();
19
20 usage() if $help;
21
22 $concurrency ||= 1;
23 $loops ||= 1;
24 $wait ||= 0;
25
26 my @urls = file2urls($file) if ($file);
27 push @urls, @ARGV;
28
29 my $num = scalar @urls;
30 warn "$num urls with $concurrency clients, $loops loops\n";
31 warn "Total: ", $num * $concurrency * $loops, " requests\n";
32 warn "wait for $wait second between requests\n";
33
34
35
36 my $pm = Parallel::ForkManager->new($concurrency);
37 for (my $i = 0; $i < $loops; $i++) {
38     for (my $child = 0; $child < $concurrency; $child++) {
39         $pm->start and next;
40             foreach my $url (@urls) {
41                 get($url) or warn "fail: $url\n";
42                 sleep($wait);
43             }
44         $pm->finish;
45     }
46     print STDERR " ... ", $num * $concurrency * ($i + 1), " requesting\r";
47 }
48 $pm->wait_all_children;
49
50 warn "\n ...done.\n";
51
52
53 sub usage {
54     warn "$0 -i urls.txt -c concurrency -n loops -w wait_interval\n",
55          " OR...\n",
56          "$0 url1 url2\n"
57     ;
58     
59     exit;
60 }
61
62 sub file2urls {
63     my $file = shift;
64     
65     open my $fh, '<', $file or die "$file: $!";
66     
67     my(@urls, $url);
68     while ($url = <$fh>) {
69         chomp $url;
70         push @urls, $url;
71     }
72     
73     return @urls;
74 }