您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python urllib2.urlopen()速度很慢,需要一种更好的方式来读取多个URL

Python urllib2.urlopen()速度很慢,需要一种更好的方式来读取多个URL

我正在使用以下现代python模块(如threading和)重写Dumb Guy的代码Queue

import threading, urllib2
import Queue

urls_to_load = [
'http://stackoverflow.com/',
'http://slashdot.org/',
'http://www.archive.org/',
'http://www.yahoo.co.jp/',
]

def read_url(url, queue):
    data = urllib2.urlopen(url).read()
    print('Fetched %s from %s' % (len(data), url))
    queue.put(data)

def fetch_parallel():
    result = Queue.Queue()
    threads = [threading.Thread(target=read_url, args = (url,result)) for url in urls_to_load]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return result

def fetch_sequencial():
    result = Queue.Queue()
    for url in urls_to_load:
        read_url(url,result)
    return result

的最佳时间find_sequencial()是2秒。最佳时间为fetch_parallel()0.9秒。

也不说thread由于GIL在Python中没有用。这是线程在Python中有用的情况之一,因为线程在I / O上被阻塞。如您在我的结果中看到的,并行案例的速度快了2倍。

python 2022/1/1 18:36:11 有229人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶