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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM