简体   繁体   English

python urllib2计时

[英]python urllib2 timing

I'd like to collect statistics related to how long each phase of a web request takes. 我想收集与Web请求的每个阶段需要多长时间相关的统计信息。 httplib offers: httplib提供:

 def run(self): conn = httplib.HTTPConnection('www.example.com') start = time.time() conn.request('GET', '/') request_time = time.time() resp = conn.getresponse() response_time = time.time() conn.close() transfer_time = time.time() self.custom_timers['request sent'] = request_time - start self.custom_timers['response received'] = response_time - start self.custom_timers['content transferred'] = transfer_time - start assert (resp.status == 200), 'Bad Response: HTTP %s' % resp.status 

Are these statistics available from a more high-level interface like urllib2 ? 这些统计数据是否来自urllib2等更高级别的界面? Is there high level library offering such statistics? 是否有提供此类统计数据的高级图书馆?

As mentioned in a related question a good way to do this now is to use the requests library. 正如在相关问题中提到的,现在执行此操作的一个好方法是使用请求库。 You can use it to measure the request latency, though I'm not sure if you can measure the content transfer timing. 您可以使用它来衡量请求延迟,但我不确定您是否可以测量内容传输时间。 You could potentially do that by comparing a HEAD request to a GET request. 您可以通过将HEAD请求与GET请求进行比较来实现。

time.time is not the most reliable and precise. time.time不是最可靠和最精确的。 You can use the timeIt module in python for your profiling purpose. 您可以在python中使用timeIt模块进行分析。 http://docs.python.org/library/timeit.html Here is a code snippet that uses timeit http://docs.python.org/library/timeit.html这是一个使用timeit的代码片段

    statmnt = 'print "Replace print with the snippet you want to profile"'
    setup = 'print "Replace this line with some snippet specific imports"' 
    n = 1 #Number of times you want the timeit module to execute the statmnt
    t = timeit.Timer(statmnt, setup)
    qTime = t.timeit(n)

In your case you will hae to give create three timeit objects, for request, response and content. 在您的情况下,您将为请求,响应和内容提供创建三个timeit对象。 Do refer the documentation for more info on the module timeit 有关模块时间的更多信息,请参阅文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM