本文介绍了获取TTFB(直到第一个字节的时间)以获取HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个加载网址并捕获响应时间的python脚本:

Here is a python script that loads a url and captures response time:

import urllib2
import time

opener = urllib2.build_opener()
request = urllib2.Request('http://example.com')

start = time.time()
resp = opener.open(request)
resp.read()
ttlb = time.time() - start

由于我的计时器环绕着整个请求/响应(包括read()),所以这将给我TTLB(到最后一个字节的时间).

Since my timer is wrapped around the whole request/response (including read()), this will give me the TTLB (time to last byte).

我也想获取TTFB(到第一个字节的时间),但不确定从哪里开始/停止我的计时. urllib2是否足够我添加TTFB计时器?如果是这样,他们会去哪里?

I would also like to get the TTFB (time to first byte), but am not sure where to start/stop my timing. Is urllib2 granular enough for me to add TTFB timers? If so, where would they go?

推荐答案

您应该使用pycurl,而不是urllib2

  1. 安装pyCurl:
    您可以使用pip/easy_install,也可以从源代码进行安装.

  1. install pyCurl:
    you can use pip / easy_install, or install it from source.

easy_install pyCurl

easy_install pyCurl

也许您应该是超级用户.

maybe you should be a superuser.

用法:

import pycurl
import sys
import json

WEB_SITES = sys.argv[1]

def main():
    c = pycurl.Curl()
    c.setopt(pycurl.URL, WEB_SITES)              #set url
    c.setopt(pycurl.FOLLOWLOCATION, 1)
    content = c.perform()                        #execute
    dns_time = c.getinfo(pycurl.NAMELOOKUP_TIME) #DNS time
    conn_time = c.getinfo(pycurl.CONNECT_TIME)   #TCP/IP 3-way handshaking time
    starttransfer_time = c.getinfo(pycurl.STARTTRANSFER_TIME)  #time-to-first-byte time
    total_time = c.getinfo(pycurl.TOTAL_TIME)  #last requst time
    c.close()

    data = json.dumps({'dns_time':dns_time,
                       'conn_time':conn_time,
                       'starttransfer_time':starttransfer_time,
                       'total_time':total_time})
    return data

if __name__ == "__main__":
    print main()

这篇关于获取TTFB(直到第一个字节的时间)以获取HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-23 09:35