猫型エンジニアのブログ

プログラム/ネットワーク系の技術関連をまとめたページです 

Eventletの使い方(クライアント版)

 PythonのモジュールEventletを触ってみます。並列プログラミング難しいです。基本的にここを参照しています。

とりあえず触ってみる

 ネットワークを介しての問い合わせはIO処理に時間がかかっているはずです。そのためGETメソッドを逐次処理する場合と、eventletを使って並列化して処理する場合それぞれでかかる時間を比較します。きっと並列処理の方が圧倒的に処理時間がかかるはずです!

並列処理版

urls = ["http://www.google.com/",
       "https://wiki.secondlife.com/",
       "http://www.yahoo.co.jp/"]

import eventlet
import time
from eventlet.green import urllib2

def fetch(url):
    body = urllib2.urlopen(url).read()
    return url, body

pool = eventlet.GreenPool()

time1 = time.time()

for url, body in pool.imap(fetch, urls):
    print "got body from", url, "of length", len(body)
time2 = time.time()

print time2
print time1
print time2 - time1

逐次処理版

urls = ["http://www.google.com/",
       "https://wiki.secondlife.com/",
       "http://www.yahoo.co.jp/"
       ]

import urllib2
import time

time1 = time.time()

for url in urls:
    body = urllib2.urlopen(url).read()
    print "got body from", url, "of length", len(body)

for url in urls:
    body = urllib2.urlopen(url).read()

time2 = time.time()
print time1
print time2
print time2 - time1

実行結果

$ python eventlet-test.py 
got body from http://www.google.com/ of length 12178
got body from https://wiki.secondlife.com/ of length 29087
got body from http://www.yahoo.co.jp/ of length 22234
1398602240.33
1398602235.75
4.57825303078 <-並列処理版の処理時間です
pidepide-no-MacBook-Air:PythonCode pide$ python eventlet-test2.py 
got body from http://www.google.com/ of length 12130
got body from https://wiki.secondlife.com/ of length 29087
got body from http://www.yahoo.co.jp/ of length 22234
1398602307.52
1398602322.26
14.7402310371 <-逐次処理版の処理時間です

 4倍以上並列処理の方が処理時間が短くなりました。うーん、これにはびっくりです。まぁ当然と言えば当然なのですが。