ようへいの日々精進XP

よかろうもん

Python で HTTP アクセスのレスポンスタイムを知る方法

tl;dr

Python で HTTP アクセスのレスポンスタイムを知る方法が気になったので調べたメモ。


参考


memo

requests モジュールを使えば良さそう

ドキュメントの抜粋。requests モジュールの Response オブジェクトで利用可能な elapsed パラメータを使えば良さそう。

The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.

Powered by Google 翻訳でざっくり意訳すると...

  • HTTP リクエストとレスポンスの間隔
  • リクエストを送信後、レスポンスのヘッダーを解析する時間

ということになるのかな...。

ちょっと試す

以下のように試してみた。

Python 2.7.6 (default, Dec 31 2013, 18:33:14) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> response = requests.get('http://pm25.test.inokara.com/kyusyu/2015-10-11.html')
>>> print response.elapsed.total_seconds()
0.135172

ほうほう。

ちょっと疑い深く別の方法でも試してみたいので以下のようなスクリプトを用意して実験。

# -*- coding: utf-8 -*-

import requests
import time

print "=== elapsed.total_seconds() を利用"
response = requests.request('GET', 'http://pm25.test.inokara.com/kyusyu/2015-10-11.html')
print response
print response.elapsed.total_seconds()
print ""

print "=== 開始の時間と終了の時間を利用"
start = time.time()
response = requests.request('GET', 'http://pm25.test.inokara.com/kyusyu/2015-10-11.html')
end = time.time()
print response
print end - start

以下のような結果となった。

#
# 一回目
#
% python test.py
=== elapsed.total_seconds() を利用
<Response [200]>
0.153672

=== 開始の時間と終了の時間を利用
<Response [200]>
0.227260112762

#
# 二回目
#
% python test.py
=== elapsed.total_seconds() を利用
<Response [200]>
0.150695

=== 開始の時間と終了の時間を利用
<Response [200]>
0.256433963776

#
# 三回目
#
% python test.py
=== elapsed.total_seconds() を利用
<Response [200]>
0.172109

=== 開始の時間と終了の時間を利用
<Response [200]>
0.25338602066

うーむ、time モジュールを前後で利用している分の時間が含まれてしまっているのか、「開始の時間と終了の時間を利用」の場合に時間を要する結果になった。


以上

どっちが良いのかな...

解らないけど elapsed.total_seconds() を利用を検討したい。