2

I have a requirement to fetch many http urls and I use AnyEvent::HTTP to do this For every URL I need to measure the time taken how can I do this ?

My code (stripped down) is here

    #!/usr/bin/perl                                                                                                                                                          

use strict;
use AnyEvent::HTTP;
use AnyEvent::Socket;
use Data::Dumper;


my $internal_ip=v192.168.2.103;   #Use this ip to bind instead of default ip. Harcoding necessary :-( using v$ip                                                         

sub prep_cb {
    my ($socket)=@_;
    my $bind = AnyEvent::Socket::pack_sockaddr undef, $internal_ip;
    # I need to start the time here                                                                                                                                      
    bind $socket, $bind
         or die "bind: $!";
}

my $url="http://192.168.2.105/echo.php";

my $anyevent = AnyEvent->condvar;
$anyevent->begin;
http_request(
    "GET" => $url,
    on_prepare =>\&prep_cb,
    sub {
        my ($data, $hdr) = @_;
        $anyevent->end;
        # I need to measure the time taken                                                                                                                               
        print Dumper([$data,$hdr]);
    }
    );
$anyevent->recv;
Ram
  • 1,155
  • 13
  • 34

2 Answers2

0

What if you replace your http_request() with the following:

my $timer;
http_request(
  "GET" => $url,
  on_prepare => sub {$timer = time; prep_cb},
  sub {
      my ($data, $hdr) = @_;
      $anyevent->end;
      print "Took " . (time - $timer) . " seconds.\n";               
      print Dumper([$data,$hdr]);
  }
);
TheAmigo
  • 1,032
  • 1
  • 10
  • 29
0

Simpler way is to have a variable and update it on on_prepare and log it after $anyevent->end as mentioned by TheAmigo

A general way to profile/time any function: Assuming your function is fetchHttpUrl($url), you could call it like this

profile(\&fetchHttpUrl, $url);

sub profile {
    my($function, @arguments) = @_;
    my $startTime = currentTimeInMilliseconds();
    $function->(@arguments);
    my $durationInMs = currentTimeInMilliseconds() - $startTime;
    print"{".getMethodNameFromPointer($function)."(".join(",", @arguments).")"."} : $durationInMs ms";
}
thepace
  • 2,221
  • 1
  • 13
  • 21