[Gevent]gevent 网络抓取小测试

早就听说gevent基于事件的异步处理能力 效率多么高,一直在项目中也很少用到,今天先来没事就学习了些简单的用法。

有个官方的教程写的很不错 中文版的地址为:http://xlambda.com/gevent-tutorial/ 学习gevent很不错的资料。


具体的理论这里不怎么说了,只是有些了解,具体的原理还不能解释的很清楚。不过协程这种概念在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的开销很小,所以还是很具有性价比的。

还有从结果中可以看到gevent和多线程都会有上下文切换,所以执行结果的线程id是乱序的,这个很好理解。

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




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值