python多线程提高速度_Python多线程速度基础测试

这篇博客探讨了在Python中使用多进程(multiprocessing)、多线程(threading)以及线程池(threadpool)进行URL内容爬取的效率。代码示例展示了不同并行方式下爬取网页HTTP状态码的时间消耗,结果显示多进程和多线程在处理大量URL时的性能差异,并讨论了适合不同场景的选择。
摘要由CSDN通过智能技术生成

#encoding=utf-8

import urllib

import threading

import multiprocessing

import threadpool

import time

from multiprocessing.dummy import Pool as ThreadPool

# import sys

# reload(sys)

# sys.setdefaultencoding("utf-8")

def get_content(url):

try:

page=urllib.urlopen(url).getcode()

print url,page

# op_httpcode_txt.write('%s%s '%(url, page))

except Exception, exception:

print exception

# op_httpcode_txt.write('exception')

# threading.Lock().release

# if __name__=="__main__":

# start=time.time()

# result=[]

# p=multiprocessing.Pool(processes=4)

# with open('url.txt','r') as f:

# for i in f.readlines():

# i=i.strip()

# result.append(p.apply_async(get_content,('%s'%i,)))

# p.close()

# for res in result:

# res.get(timeout=5)

# end=time.time()

# print end-start #5.72699999809 7.3s

# c=raw_input('anything:')

if __name__ == '__main__':

start=time.time()

with open('url.txt','r') as f:

for i in f.readlines():

i=i.strip()

# threading.Lock()

p=threading.Thread(target=get_content,args=(i,))

p.start()

end=time.time()

print end-start # 5.1s

print 'current has %d threads' %(threading.activeCount())

# c=raw_input('anything:')

# if __name__ == '__main__':

# start=time.time()

# pool=ThreadPool(4)

# page=[x.strip() for x in open('url.txt').readlines()]

# results=pool.map(get_content,page)

# pool.close()

# pool.join()

# end=time.time()

# print end-start #5.82299995422s 6.2s

# if __name__ == '__main__':

# start=time.time()

# pool = threadpool.ThreadPool(4)

# i=[i.strip() for i in open('url.txt').readlines()]

# reqs = threadpool.makeRequests(get_content,i)

# [pool.putRequest(req) for req in reqs]

# pool.wait()

# end=time.time()

# print end-start #6.45700001717s 6.7s

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值