转-python异步IO-asyncio
原文连接 http://blog.chinaunix.net/uid-190176-id-4223282.html
import argparse
import asyncio
import functools
import logging
import random
import urllib.parse loop = asyncio.get_event_loop() @asyncio.coroutine
def print_http_headers(no, url, keepalive):
url = urllib.parse.urlsplit(url)
wait_for = functools.partial(asyncio.wait_for, timeout=3, loop=loop)
query = ('HEAD {url.path} HTTP/1.1\r\n'
'Host: {url.hostname}\r\n'
'\r\n').format(url=url).encode('utf-8') rd, wr = yield from wait_for(asyncio.open_connection(url.hostname, 80))
while True:
wr.write(query) while True:
line = yield from wait_for(rd.readline())
if not line: # end of connection
wr.close()
return no
line = line.decode('utf-8').rstrip()
if not line: # end of header
break
logging.debug('(%d) HTTP header> %s' % (no, line)) yield from asyncio.sleep(random.randint(1, keepalive//2)) @asyncio.coroutine
def do_requests(args):
conn_pool = set()
waiter = asyncio.Future() def _on_complete(fut):
conn_pool.remove(fut)
exc, res = fut.exception(), fut.result()
if exc is not None:
logging.info('conn#{} exception'.format(exc))
else:
logging.info('conn#{} result'.format(res)) if not conn_pool:
waiter.set_result('event loop is done') for i in range(args.connections):
fut = asyncio.async(print_http_headers(i, args.url, args.keepalive))
fut.add_done_callback(_on_complete)
conn_pool.add(fut)
if i % 10 == 0:
yield from asyncio.sleep(0.01) logging.info((yield from waiter)) def main():
parser = argparse.ArgumentParser(description='asyncli')
parser.add_argument('url', help='page address')
parser.add_argument('-c', '--connections', type=int, default=1,
help='number of connections simultaneously')
parser.add_argument('-k', '--keepalive', type=int, default=60,
help='HTTP keepalive timeout')
args = parser.parse_args() logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
loop.run_until_complete(do_requests(args))
loop.close() if __name__ == '__main__':
main()
- # ../sbin/nginx
- # ps ax | grep nginx
- 2007 ? Ss 0:00 nginx: master process ../sbin/nginx
- 2008 ? S 0:00 nginx: worker process
- $ python asyncli.py http://10.211.55.8/ -c 10000
- # tail -1000000 access.log | awk '{ print $4 }' | sort | uniq -c | awk '{ cnt+=1; sum+=$1 } END { printf "avg = %d\n", sum/cnt }'
- avg = 548
- VIRT RES SHR S %CPU %MEM TIME+ COMMAND
- 657m 115m 3860 R 60.2 6.2 4:30.02 python
- 54208 10m 848 R 7.0 0.6 0:30.79 nginx
转-python异步IO-asyncio的更多相关文章
- Python异步IO --- 轻松管理10k+并发连接
前言 异步操作在计算机软硬件体系中是一个普遍概念,根源在于参与协作的各实体处理速度上有明显差异.软件开发中遇到的多数情况是CPU与IO的速度不匹配,所以异步IO存在于各种编程框架中,客户端比如浏览 ...
- python异步IO编程(一)
python异步IO编程(一) 基础概念 协程:python generator与coroutine 异步IO (async IO):一种由多种语言实现的与语言无关的范例(或模型). asyncio ...
- python异步IO编程(二)
python异步IO编程(二) 目录 开门见山 Async IO设计模式 事件循环 asyncio 中的其他顶层函数 开门见山 下面我们用两个简单的例子来让你对异步IO有所了解 import asyn ...
- Python异步IO
在IO操作的过程中,当前线程被挂起,而其他需要CPU执行的代码就无法被当前线程执行了. 我们可以使用多线程或者多进程来并发执行代码,为多个用户服务. 但是,一旦线程数量过多,CPU的时间就花在线程切换 ...
- python -- 异步IO 协程
python 3.4 >>> import asyncio >>> from datetime import datetime >>> @asyn ...
- Python异步IO之协程(一):从yield from到async的使用
引言:协程(coroutine)是Python中一直较为难理解的知识,但其在多任务协作中体现的效率又极为的突出.众所周知,Python中执行多任务还可以通过多进程或一个进程中的多线程来执行,但两者之中 ...
- Python - 异步IO\数据库\队列\缓存
协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程,协程一定是在单线程运行的. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和 ...
- Python 异步IO、IO多路复用
事件驱动模型 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...
- python 异步IO
参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143208573 ...
- python 异步IO( asyncio) 协程
python asyncio 网络模型有很多中,为了实现高并发也有很多方案,多线程,多进程.无论多线程和多进程,IO的调度更多取决于系统,而协程的方式,调度来自用户,用户可以在函数中yield一个状态 ...
随机推荐
- es-01-简介
1, 基于lucene的实时搜索软件 分布式的restful风格的搜索和数据分析引擎, 2, 和kibana, logstash 构成 elk生态圈 es: 数据存储和查询 kibana: 可视化 l ...
- [Python学习笔记-002] lambda, map, filter and reduce
1. lambda lambda, 即匿名函数,可以理解为跟C语言的宏类似.例如: >>> max = lambda x, y: x if x > y else y >& ...
- 数据序列化导读(3)[JSON v.s. YAML]
前面两节介绍了JSON和YAML,本文则对下面的文章做一个中英文对照翻译. Comparison between JSON and YAML for data serialization用于数据序列化 ...
- linux下开启、关闭、重启mysql服务
linux下开启.关闭.重启mysql服务命令 一. 启动1.使用 service 启动:service mysql start2.使用 mysqld 脚本启动:/etc/inint.d/mysql ...
- zoj 2818 Root of the Problem(数学思维题)
题目链接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2818 题目描述: Given positive integer ...
- asp.net MVC 的处理流程
之前把笔记都放在空间日志中隐藏起来,今天看到这句话:作为经常从网上索取免费资料的一员,要有回报的思想,也为了让更多的人少走些弯路,想想自己不能这么自私,所以把空间日志搬到博客园来.闲话不说,直接开始. ...
- WPF备忘录(1)有笑脸,有Popup
1.画个笑脸给大家娱乐一下: <Canvas Width="200" Height="180" VerticalAlignment="Cente ...
- SQL SERVER存储过程中使用事务
存储过程格式: CREATE PROCEDURE YourProcedure AS BEGIN SET NOCOUNT ON; BEGIN TRY---------------------开始捕捉异常 ...
- Code Signal_练习题_chessBoardCellColor
Given two cells on the standard chess board, determine whether they have the same color or not. Exam ...
- Loadrunner脚本优化-参数化之关联MySQL数据库获取数据
脚本优化-参数化之关联MySQL数据库获取数据 by:授客 QQ:1033553122 测试环境: Loadrunner 11 Win7 64位 实操: 1. 安装MySQL ODBC驱动程序 O ...