作者uranusjr (←这人是超级笨蛋)
看板Python
标题Re: [心得] 爬虫实做分享
时间Mon Mar 27 22:35:17 2017
※ 引述《zerof (猫橘毛发呆雕像)》之铭言:
※ 引述《zerof (猫橘毛发呆雕像)》之铭言:
: 这疑虑是对的, L:48 的 for-loop 的确会导致 L:54 接近循序执行,在 scheduler
: 没满的情况下的确会比较慢。
: 这部份的考量主要在於 L:54 request 的是主网站而非图床,避免大量 requests
: 导致其他使用者的延迟。
: L:64 则是大量 requests 会导致 WinSock 炸掉.... http://imgur.com/zA94lRJ ,
: 只好加个 limit 再用 wait() 来跑 。 (它炸太快我也不知道上限到底是多少....)
: 这里一样的问题是 async.wait() 会 block 到所有的 task done 才跑下一轮,在某
: 种意义上 scheduler 也是没有满的状态。
这个技巧叫做 throttling,是这个问题的解法没错
但与其手动 delay,更好的方法是直接限制同时可以有几个 tasks
最简单的方法是加上一个 semaphore:
semaphore = asyncio.Semaphore(CONCURRENT_TASK_COUNT)
async def throttle(f):
async with semaphore:
await f
await asyncio.wait([throttle(f) for f in fs])
只要调整 CONCURRENT_TASK_COUNT
就可以保证 wait 一次只会同时等这麽多个 tasks
前面 fetch_imgs 部分也可以类似处理
1F:→ s860134: 其实这个例子比较好用 threading 就好,之前 pyCon 有讲 03/27 21:07
2F:→ s860134: 说 requests 在做档案 IO 时好像放掉 GIL? 03/27 21:07
: 这蛮有趣的XD, requests 下层的 library 是用 urllib3 是 native python 写的,
: 相依性是零,有 connectionpool ,没猜错的话是用 threading pool 。
: 而实际上 GIL 在呼叫用 C 写的函式的时候都会被释放,所以在用 open 开档案的时
: 候是一定会释放 GIL 的。
: 就算是这样, asyncio 实际上还是比 multithread 快,可以参考这个影片:
: https://youtu.be/M8Z65tAl5l4
这边的关键已经不是速度了, 前面就证明了速度太快也没用, server hold 不住
更重要的问题是 async 加上 synchronization primitives 可读性会快速下降
(这也是为什麽最近 reactive programming 这麽红, 不过那是另一个议题)
在速度不那麽重要的状况下, threading idiom 会好懂一些
--
Les grandes et les meilleurs
tone from "Zadok the Priest"
Eine grosse stattliche Veranstaltung
by F. Handel
THE MAIN EVENT! These are the men
Sie sind die Besten
"Champions League" by Tony Britten THESE ARE THE CHAMPIONS!
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 218.161.19.12
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1490625319.A.738.html
※ 编辑: uranusjr (218.161.19.12), 03/27/2017 22:40:52
3F:推 zerof: Semaphore 解得蛮漂亮的XD 03/27 22:42