一个python多线程小例子

一个python多线程小例子:

我拿正常for循环多线程 做时间对比:

import time
from urllib2 import urlopen
from multiprocessing.dummy import Pool as ThreadPool

"""
一个简单的多线程例子.
"""

urls = [
    "http://www.python.org",
    "http://www.python.org/about/",
    "http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html",
    "http://www.python.org/doc/",
    "http://www.python.org/download/",
    "http://www.python.org/getit/",
    "http://www.python.org/community/",
    "https://wiki.python.org/moin/",
    "http://planet.python.org/",
    ]


def for_loop():
    start = time.time()
    for url in urls:
        urlopen(url)
    print ("for loop time:%s" % (time.time()-start))


def thread_pool(pool_size):
    start = time.time()
    pool = ThreadPool(pool_size)
    pool.map(urlopen, urls)
    pool.close()
    pool.join()
    print ("thread pool time:%s" % (time.time()-start))


for_loop()
thread_pool(8)

可以看到,多线程消耗时间少很多---------------------->

 

你可能感兴趣的:(python)