Response time for urllib in python

此生再无相见时 提交于 2019-11-29 10:32:11

问题


I want to get response time when I use urllib. I made below code, but it is more than response time. Can I get the time using urllib or have any other method?

import urllib
import datetime

def main():
    urllist = [
        "http://google.com",
    ]

    for url in urllist:
        opener = urllib.FancyURLopener({})
        try:
            start = datetime.datetime.now()
            f = opener.open(url)
            end = datetime.datetime.now()
            diff = end - start
            print int(round(diff.microseconds / 1000))
        except IOError, e:
            print 'error', url
        else:
            print f.getcode(), f.geturl()

if __name__ == "__main__":
    main()

回答1:


Save yourself some hassle and use the requests module. In its responses it provides a datetime.timedelta field called 'elapsed' that lets you know how long the request took.

>>> import requests
>>> response = requests.get('http://www.google.com')
>>> print response.elapsed
0:00:01.762032
>>> response.elapsed
datetime.timedelta(0, 1, 762032)


来源:https://stackoverflow.com/questions/16931280/response-time-for-urllib-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!