[Gevent]gevent 網絡抓取問答

我據說過gevent基於事件的異步處理功能 如何高效率,該項目已不多使用,今天是沒什麼學習一些簡單的使用。python

有正式書面一個很是好的教程 中國版的地址:http://xlambda.com/gevent-tutorial/ 學習gevent很是不錯的資料。golang


詳細的理論這裏不怎麼說了,僅僅是有些瞭解。詳細的原理還不能解釋的很是清楚。json

只是協程這樣的概念在golang裏面很是多。網絡

寫了一個訪問網絡,使用同步操做,gevent 和 多線程對照的樣例。多線程


#!/usr/bin/python
# -*- coding: utf-8 -*-
# python2.7x
# gevent_urllib2.py
# author: orangelliu
# date: 2014-08-20

import gevent.monkey
gevent.monkey.patch_socket()

import gevent
import urllib2
import json
import threading

def fetch(pid):
	response = urllib2.urlopen('http://www.orangleliu.info')
	result = response.read()
	btypes = len(result)

	print 'process %s : %s'%(pid, btypes)

def synchronous():
	for i in range(10):
		fetch(i)

def asynchonous():
	threads = []
	for i in range(10):
		threads.append(gevent.spawn(fetch,i))
	gevent.joinall(threads)

def mulithread():
	threads = []
	for i in range(10):
		th = threading.Thread(target=fetch, args=(i,))
		threads.append(th)

	for thread in threads:
		thread.start()

	for thread in threads:
		threading.Thread.join(thread)

import time
print 'sync....'
ss = time.time()
synchronous()
print 'sync time is %s'%(time.time()-ss)

print 'async'
sa = time.time()
asynchonous()
print 'async time is %s'%(time.time()-sa)

print 'async'
sm = time.time()
mulithread()
print 'thread time is %s'%(time.time()-sm)


這結果僅僅能做爲參考。因爲不一樣的時間網絡情況有差別,但是總的來講多線程最快。gevent還行,同步最慢。

但是考慮到gevent的開銷很是小。因此仍是很是具備性價比的。app

還有從結果中可以看到gevent和多線程都會有上下文切換,因此運行結果的線程id是亂序的,這個很是好理解。python2.7

sync....
process 0 : 8657
process 1 : 8657
process 2 : 8657
process 3 : 8657
process 4 : 8657
process 5 : 8657
process 6 : 8657
process 7 : 8657
process 8 : 8657
process 9 : 8657
sync time is 2.7610001564
async
process 8 : 8657
process 7 : 8657
process 6 : 8657
process 2 : 8657
process 5 : 8657
process 3 : 8657
process 0 : 8657
process 4 : 8657
process 1 : 8657
process 9 : 8657
async time is 1.50199985504
async
process 0 : 8657
process 1 : 8657
process 3 : 8657
process 4 : 8657
process 5 : 8657
process 7 : 8657
process 9 : 8657
process 8 : 8657
process 6 : 8657
process 2 : 8657
thread time is 0.986000061035
本文出自  orangleliu筆記本  博客,請務必保留此出處http://blog.csdn.net/orangleliu/article/details/38715763




版權聲明:本文orangleliu(http://blog.csdn.net/orangleliu/)原創文章,轉載文章,請聲明。異步

相關文章
相關標籤/搜索