[Gevent]gevent 网络抓取小测试
来源:互联网 发布:淘宝客服表格 编辑:程序博客网 时间:2024/04/28 14:48
早就听说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-20import gevent.monkeygevent.monkey.patch_socket()import geventimport urllib2import jsonimport threadingdef 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 timeprint '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 : 8657process 1 : 8657process 2 : 8657process 3 : 8657process 4 : 8657process 5 : 8657process 6 : 8657process 7 : 8657process 8 : 8657process 9 : 8657sync time is 2.7610001564asyncprocess 8 : 8657process 7 : 8657process 6 : 8657process 2 : 8657process 5 : 8657process 3 : 8657process 0 : 8657process 4 : 8657process 1 : 8657process 9 : 8657async time is 1.50199985504asyncprocess 0 : 8657process 1 : 8657process 3 : 8657process 4 : 8657process 5 : 8657process 7 : 8657process 9 : 8657process 8 : 8657process 6 : 8657process 2 : 8657thread time is 0.986000061035本文出自 “orangleliu笔记本” 博客,请务必保留此出处http://blog.csdn.net/orangleliu/article/details/38715763
0 0
- [Gevent]gevent 网络抓取小测试
- gevent
- GEVENT
- gevent
- gevent
- Gevent tutorial (Gevent中文教程,Gevent中文翻译)
- python性能测试之 gevent 效果不错
- gevent 安装
- gevent 一点点
- python gevent
- gevent 安装
- mac gevent
- linux gevent
- gevent-socketio
- gevent模块
- gevent 小结
- gevent tutorial
- ZeroMQ Gevent
- “是啊,不是姓朱的那种败类就好,
- c# 接口IComparer<T>
- 特别是要钱没钱呐,真是酸的一无是处,心底不禁自卑起来。
- setup and test samba server
- 好想抱着你睡觉
- [Gevent]gevent 网络抓取小测试
- 13点,你懂的
- 图 - 图的存储结构 - 邻接矩阵表示法
- 我打我打我打
- [1] 算法之路 - 选择排序
- lisa素材
- uva 1356 - Bridge(积分+二分)
- 【Webkit学习】Android4.4 Chromium WebView学习
- Windows平台下Git服务器搭建