[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/)原创文章,转载文章,请声明。异步

相关文章
相关标签/搜索