Hateburo: kazeburo hatenablog

SRE / 運用系小姑 / Goを書くPerl Monger

AnyEvent::HTTPでサーバへの接続に掛かった時間とレスポンスに掛かった時間を取得する方法

深遠な理由で、connect(2) に掛かった時間と、リクエストを送ってレスポンスが得られるまでに掛かった時間を出したい

#!/usr/bin/perl

use strict;
use warnings;
use AnyEvent::HTTP;
use AnyEvent::Socket;
use AnyEvent::DNS::Cache::Simple;
use Time::HiRes;

my $guard = AnyEvent::DNS::Cache::Simple->register;

for my $i ( 1..3 ) {
    my $cv = AE::cv;
    my @times;
    http_get "http://livedoor.blogimg.jp/",
        persistent => 0,
        keepalive => 0,
        tcp_connect => sub {
            my ($host, $service, $connect_cb, $prepare_cb) = @_;
            push @times, Time::HiRes::time();
            tcp_connect( $host, $service,
                         sub {
                             push @times, Time::HiRes::time();
                             $connect_cb->(@_)
                         },
                         $prepare_cb);
        },
        sub {
                push @times, Time::HiRes::time();
                warn sprintf '%s connect: %s req_to_res: %s', 
                    $i,
                    int(($times[1] - $times[0]) * 1_000_000), 
                    int(($times[2] - $times[1]) * 1_000_000);
                $cv->send;
            };
    $cv->recv;
}

上のコードを実行するとこんな感じで取れた。

% perl ae_http.pl
1 connect: 41758 req_to_res: 12425 at ae_http.pl line 30.
2 connect: 11051 req_to_res: 11618 at ae_http.pl line 30.
3 connect: 10995 req_to_res: 11157 at ae_http.pl line 30.

2回目以降が速いのはDNSのキャッシュが効く為です