lua协程并发下载简单测试
下载8个1m大小文件,测试五次分别耗时12.038s,10.316s,8.955s,11.275s,9.499s(lua代码实现如下)
require "socket" --host = "www.w3.org"
--file = "/TR/REC-html32.html" function lua_string_split(str, split_char) --字符串拆分 local sub_str_tab = {};
while (true and str ~= nil) do
local pos = string.find(str, split_char);
if (not pos) then
sub_str_tab[#sub_str_tab + ] = str;
break;
end
local sub_str = string.sub(str, , pos - );
sub_str_tab[#sub_str_tab + ] = sub_str;
str = string.sub(str, pos + , #str);
end return sub_str_tab;
end function download(url)
local infolist = lua_string_split(url,"/")
local cache_file = infolist[#infolist] local host = infolist[]
local pos = string.find(url, host)
local file = nil
if pos then
file = string.sub(url, pos + #host)
end
pos = nil local out = io.open(cache_file,"wb")
local c = assert(socket.connect(host, ))
local count =
local pos = nil c:send("GET " ..file .." HTTP/1.0\r\n\r\n")
while true do
local s, status, partial = receive(c)
count = count + #(s or partial)
local data = s or partial if data then
if pos == nil then --去除响应头
pos = string.find(data, "\r\n\r\n")
if pos then
out:write(string.sub(data, pos + #"\r\n\r\n"))
end
else
out:write(data)
end
end
if status == "closed" then break end
end
c:close()
-- print(file, count)
out:close()
-- os.execute("del " .. cache_file)
end function receive(connection)
connection:settimeout()
local s, status, partial = connection:receive(^*)
if status == 'timeout' then
coroutine.yield(connection)
end
return s or partial, status
end threads = {} function get(url)
local co = coroutine.create(function ()
download(url)
end)
table.insert(threads, co)
end function dispatch()
local i =
local connections = {}
while true do
if threads[i] == nil then
if threads[] == nil then break end
i =
connections = {}
end
local status, res = coroutine.resume(threads[i])
if not res then
table.remove(threads, i)
else
i = i +
connections[#connections + ] = res
if #connections == #threads then
local a, b, err = socket.select(connections)
for k, v in pairs(a) do
--print(k, 'a=a', v)
end
for k, v in pairs(b) do
--print(k, 'b=b', v)
end
end
end
end
end --get("http://www.w3.org/TR/REC-html32.html")
--get("http:///1/将夜") --下载中文会出错 local files = {'a','b','c','d','e','f','g','h'}
for i=,#files do
get("http://127.0.0.1/" .. files[i] .. ".file")
end dispatch() print(os.clock())
下载8个1m大小文件,测试五次分别耗时12.324s,14.407s,13.883s,15.188s,8.887s(python代码实现如下)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import time
import urllib
import urllib2
import multiprocessing
from time import clock def worker(pline): rinfo = pline.split("/")
filename, url = rinfo[len(rinfo)-1], pline filename = urllib2.unquote(filename)
try:
f = urllib2.urlopen(url,timeout=10800)
with open(filename, "wb") as code:
code.write(f.read())
except:
print sys.exc_info()
return 0 return 1
#
# main
# if __name__ == "__main__": start = clock()
pool_size = multiprocessing.cpu_count() * 2
pool = multiprocessing.Pool(processes=pool_size) for i in ["a","b","c","d","e","f","g","h"]:
url = "http://127.0.0.1/"+i+".file"
pool.apply_async(worker, (url,)) pool.close()
pool.join()
end = clock()
print (end-start)
就算把python的进程池设置为1个,利用单cpu跑,耗时结果测试也是一样的。看不出来lua的协程对性能有多大的提升,感觉用多进程能实现的,就还是不要去折腾协程吧,毕竟协程不能利用多核的优势,编程也麻烦很多。
附:lua使用luasocket库发起http请求很方便
local http = require("socket.http")
local chunkbody = {}
res, code, headers = http.request {
method = "GET",
url = "http://127.0.0.1/get.php",
sink = ltn12.sink.table(chunkbody)
}
if res ~= nil then
print(code)
for k,v in pairs(headers) do
print(k .. ":" .. v)
end
print(table.concat(chunkbody))
else
io.write(code .. "\n")
end
--res, code, headers = http.request("http://127.0.0.1/post","name=admin&passwd=adminpwd")
local postdata = "name=admin&passwd=adminpwd"
chunkbody = {}
res, code, headers = http.request {
method = "POST",
url = "http://127.0.0.1/post",
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
["Content-Length"] = string.len(postdata)
},
source = ltn12.source.string(postdata),
sink = ltn12.sink.table(chunkbody)
}
if res ~= nil then
print(code)
for k,v in pairs(headers) do
print(k .. ":" .. v)
end
print(table.concat(chunkbody))
else
io.write(code .. "\n")
end
--[[
200
connection:close
content-type:text/html
date:Sun, 16 Nov 2014 16:02:16 GMT
transfer-encoding:chunked
x-powered-by:PHP/5.3.3
server:openresty/1.7.2.1
a and b
201
connection:close
content-type:application/octet-stream
date:Sun, 16 Nov 2014 16:02:16 GMT
transfer-encoding:chunked
server:openresty/1.7.2.1
pass
--]]
lua协程并发下载简单测试的更多相关文章
- python 协程并发下载图片
1 import aiohttp 2 import asyncio 3 import time 4 5 async def dl_coroutine(session,url): 6 print('开始 ...
- Lua协程-测试3
print("Lua 协程测试3") -- 实现消费者-生产者关系(生产一个就消费一个) count = -- 生产总数 -- 生产者 local newProductorCo = ...
- Lua协程-测试2
print("Lua 协程测试2") function testFun(n) print("into foo,n = "..n) * n) -- 挂起co协程 ...
- 大富翁开发日记:一、使用巨型lua协程
一个大胆的尝试:使用巨型lua协程来表示整个“一局”流程. lua协程是一个很另类的功能,有并发的影子但又不是真的并发,所以真正拿它来做大功能框架的范例不多,通常用于一些小型trick式设计.但这次我 ...
- Openresty Lua协程调度机制
写在前面 OpenResty(后面简称:OR)是一个基于Nginx和Lua的高性能Web平台,它内部集成大量的Lua API以及第三方模块,可以利用它快速搭建支持高并发.极具动态性和扩展性的Web应用 ...
- Lua 协程coroutine
协程和一般多线程的区别是,一般多线程由系统决定该哪个线程执行,是抢占式的,而协程是由每个线程自己决定自己什么时候不执行,并把执行权主动交给下一个线程. 协程是用户空间线程,操作系统其存在一无所知,所以 ...
- [转]-Lua协程的实现
协程是个很好的东西,它能做的事情与线程相似,区别在于:协程是使用者可控的,有API给使用者来暂停和继续执行,而线程由操作系统内核控制:另 外,协程也更加轻量级.这样,在遇到某些可能阻塞的操作时,可以使 ...
- lua协程实现
协程是个很好的东西,它能做的事情与线程相似,区别在于:协程是使用者可控的,有API给使用者来暂停和继续执行,而线程由操作系统内核控制:另外,协程也更加轻量级.这样,在遇到某些可能阻塞的操作时,可以使用 ...
- Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就绪,挂起,运行) ,***协程概念,yield模拟并发(有缺陷),Greenlet模块(手动切换),Gevent(协程并发)
Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就 ...
随机推荐
- Winform中上传、下载文件选择打开文件的位置
打开将要上传的文件 var fileName="";OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.Mul ...
- c++ primer plus 习题答案(1)
c++ primer plus 习题答案用的是第五版,IDE仍然是vs2013.我只标注了题号,具体的题目找下书上对应内容吧. p110.8 #include<iostream> #inc ...
- Lua for Windows入门01
由于项目紧急,我都没来得及研究lua的基本知识就直接持枪上阵了.在实施编写的过程中,却次发现编程语言如此之美,第一次. 随着Lua+for+Windows+5.1.4-45版本的完全安装,最后跳出了一 ...
- (总结)Nginx/LVS/HAProxy负载均衡软件的优缺点详解
PS:Nginx/LVS/HAProxy是目前使用最广泛的三种负载均衡软件,本人都在多个项目中实施过,参考了一些资料,结合自己的一些使用经验,总结一下. 一般对负载均衡的使用是随着网站规模的提升根据不 ...
- hdu 4033 Regular Polygon 计算几何 二分+余弦定理
题目链接 给一个n个顶点的正多边形, 给出多边形内部一个点到n个顶点的距离, 让你求出这个多边形的边长. 二分边长, 然后用余弦定理求出给出的相邻的两个边之间的夹角, 看所有的加起来是不是2Pi. # ...
- Python的maketrans() 方法
描述 Python maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标. 注:两个字符 ...
- curl: (6) Couldn’t resolve host ‘www.ttlsa.com’
上周, 部分站点出现Couldn't resolve host.....问题, 导致公司所有走api的程序都无法正常使用(系统redhat 6.3的都出现问题, redhat 5一切OK). 最 ...
- HDU 5820 Lights(扫描线+zkw线段树)
[题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=5820 [题目大意] 在一个大小为50000*50000的矩形中,有n个路灯. 询问是否每一对路灯之 ...
- retina屏实现border边框1px
.border { position: relative; width: 300px; height: 200px; } .border:after { border: 1px solid #ff33 ...
- ZOJ 3080 ChiBi(spfa)
ZOJ Problem Set - 3080 ChiBi Time Limit: 5 Seconds Memory Limit: 32768 KB watashi's mm is so pr ...