python urllib2计时

use*_*401 7 python timer urllib2 httplib

我想收集与Web请求的每个阶段需要多长时间相关的统计信息.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
Run Code Online (Sandbox Code Playgroud)

这些统计数据是否来自更高级别的界面urllib2?是否有提供此类统计数据的高级图书馆?

Max*_*dal 0

time.time并不是最可靠、最精确的。您可以使用 python 中的 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)
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您必须创建三个 timeit 对象,用于请求、响应和内容。请参阅文档以获取有关 timeit 模块的更多信息