python httplib和urllib的性能比较

httplib代码:

        urlParseResult = urlparse(url)
        host = urlParseResult.hostname
        path = urlParseResult.path
        conn = httplib.HTTPConnection(host)
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        conn.putheader("Authorization", "Basic %s" % base64string)
        conn.endheaders()  
        
        conn.request("GET", path)
      
        try:
            with open(localLogFile, "wb") as code1:     
                with contextlib.closing(conn) as conn:
                    response = conn.getresponse()
                    while True:    
                        data = response.read(defaultBlock)
                        if not len(data):
                            print str(self.logDate)+"-"+localLogFileName+"获取成功!"
                            return
                        else: 
                            code1.write(data)
        except urllib2.HTTPError as httpError:
            if httpError.code == httplib.NOT_FOUND:
                print url+"is not found,404"
            else:
                raise

urllib代码:

        defaultBlock = 2048
        base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
        conn = urllib2.Request(url)
        conn.add_header("Authorization", "Basic %s" % base64string)   
        try:
            with open(localLogFile, "wb") as code1:     
                with contextlib.closing(urllib2.urlopen(conn)) as result:
                    while True:    
                        data = result.read(defaultBlock)
                        if not len(data):
                            print str(self.logDate)+"-"+localLogFileName+"获取成功!"
                            return
                        else: 
                            code1.write(data)
        except urllib2.HTTPError as httpError:
            if httpError.code == httplib.NOT_FOUND:
                print url+"is not found,404"
            else:
                raise

执行效率代码:

from timeit import Timer
 t1 = Timer('doGetLogByConfig()', 'from __main__ import doGetLogByConfig')
print t1.timeit(1)

结果:

httplib时间:
45.4764687239
urllib时间:
64.3462849881

转载于:https://www.cnblogs.com/beiyeren/p/4046139.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值