print usage if no arguments
[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 qw(:config posix_default no_ignore_case gnu_compat);
8 use Parallel::ForkManager;
9 use LWP::Simple;
10 use Time::HiRes qw(sleep);
11
12 usage() if (@ARGV == 0);
13
14 GetOptions(
15     'h|help'            => \ my $help,
16     'i|inputfile=s'     => \ my $file,
17     'c|concurrency=i'   => \ my $concurrency,
18     'n|loops=i'         => \ my $loops,
19     'w|wait=f'          => \ my $wait,
20 ) or usage();
21
22 usage() if $help;
23
24 $concurrency ||= 1;
25 $loops ||= 1;
26 $wait ||= 0;
27
28 my @urls = file2urls($file) if ($file);
29 push @urls, @ARGV;
30
31 my $num = scalar @urls;
32 warn "$num urls with $concurrency clients, $loops loops\n";
33 warn "Total: ", $num * $concurrency * $loops, " requests\n";
34 warn "wait for $wait second between requests\n";
35
36
37
38 my $pm = Parallel::ForkManager->new($concurrency);
39 for (my $child = 0; $child < $concurrency; $child++) {
40     if ($pm->start) {
41         warn "forks $child/$concurrency child ...\n";
42         next;
43     }
44         for (my $i = 0; $i < $loops; $i++) {
45             print STDERR "processing $i/$loops loop\r";
46             foreach my $url (@urls) {
47                 get($url) or warn "fail: $url\n";
48                 sleep($wait);
49             }
50         }
51     $pm->finish;
52 }
53 $pm->wait_all_children;
54
55 warn "\n ...done.\n";
56
57
58 sub usage {
59     warn "$0 -i urls.txt -c concurrency -n loops -w wait_interval\n",
60          " OR...\n",
61          "$0 url1 url2\n"
62     ;
63     
64     exit;
65 }
66
67 sub file2urls {
68     my $file = shift;
69     
70     open my $fh, '<', $file or die "$file: $!";
71     
72     my(@urls, $url);
73     while ($url = <$fh>) {
74         chomp $url;
75         push @urls, $url;
76     }
77     
78     return @urls;
79 }