zoukankan      html  css  js  c++  java
  • python requests模块中返回时间elapsed解析

    一、问题:

    Python 中requests库在发送http请求时相当方便好用,但在使用时一直受一个问题困扰,怎么才能查看请求时长呢?

    自己写时间函数再相减?NO,这个方法肯定不行。

    二、解决:

    好吧。我们还是看看requests管方文档,功夫不负有心人,管网API竟然后介绍是:

    elapsed = None
    The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument.

    看不懂吧,切完回requests中文文档,Opps,没有翻译,只能靠自己了。

    中文大致理解如下:

    在发送请求和响应到达之前耗费的时间差(timedelta),指发送第一个byte数据头至处更完最后一个数据头之间,所以这个时长不受相应的内容影响。

    看完后,是不是还云里雾里,没关系,我们看看源码,requests对elapsed方法的源码如下:

            # Get the appropriate adapter to use
            adapter = self.get_adapter(url=request.url)
    
            # Start time (approximately) of the request
            start = datetime.utcnow()
    
            # Send the request
            r = adapter.send(request, **kwargs)
    
            # Total elapsed time of the request (approximately)
            r.elapsed = datetime.utcnow() - start

    从源码中我们可以看到使用的datetime函数来计算时间差。

    datetime是什么?不懂,来看文档吧。

    classmethod datetime.utcnow() 
    Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. See also now().

    返回UTC日期和时间,UTC是什么?看看解释:Coordinated Universal Time 世界统一时间,世界标准时间

    所以,你不用担心你发的请求的客户端与服务器时间不一致这种问题。

    三:深入理解:

    最后,问题来了,返回的时间是什么单位呢?

    我们自己写个脚本就什么都知道了:

    import datetime
    import time
    a=datetime.datetime.now()
    time.sleep(0.1) #睡眠0.1秒
    b=datetime.datetime.now()
    print b-a

    结果为:

    >>> 
    0:00:00.100000

    所以,得知,单位为微秒、微秒、

    四:对比

    既然知道了使用,那么,你肯定会问,这个时间准吗?

    我们用jmeter来对比,访问baidu

    jmeter配置如下:

    运行结果的聚合报告我们看看:

    结果为204ms

    我们再次用requests来试试,代码如下:

    import requests
    r=requests.get('http://www.baidu.com')
    print r.elapsed.microseconds/1000.

    结果:

    >>> 
    138.0

    138ms

    结果差不多。

    这里我又试了内部系统真正的的接口数据

    可以得知,差距不太大,数据我们可以还是有参考价值的。

    参考:

    Requests文档:http://cn.python-requests.org/zh_CN/latest/api.html?highlight=elapsed#requests.Response.elapsed

    datatime文档:https://docs.python.org/2.7/library/datetime.html?highlight=datetime#module-datetime

    其它解释:http://bbs.csdn.net/topics/390898823

  • 相关阅读:
    iOS万能跳转界面的方法
    CocoaPods版本更新
    iOS--开发小技巧(持续更新)
    RunTime--手势应用场景(很方便)
    牛逼的标签效果(封装好)
    直播点赞动画
    UI基础--自定义UISwitch
    StatusBar 更改状态栏颜色(ios7)
    ios版本更新提示
    IOS 两个UIImage 合成一个Image
  • 原文地址:https://www.cnblogs.com/landhu/p/5442069.html
Copyright © 2011-2022 走看看