我有Python代码,它运行10个GET请求并测量响应时间:
from datetime import datetime
from requests_futures.sessions import FuturesSession
import requests
class CustomSession(FuturesSession):
def __init__(self, *args, **kwargs):
super(CustomSession, self).__init__(*args, **kwargs)
self.timing = {}
self.timing = {}
def request(self, method, url, *args, **kwargs):
background_callback = kwargs.pop('background_callback', None)
test_id = kwargs.pop('test_id', None)
# start counting
self.timing[test_id] = {}
self.timing[test_id]['cS'] = datetime.now()
def time_it(sess, resp):
# here if you want to time the server stuff only
self.timing[test_id]['cE'] = datetime.now()
if background_callback:
background_callback(sess, resp)
# here if you want to include any time in the callback
return super(CustomSession, self).request(method, url, *args,
background_callback=time_it,
**kwargs)
# using requests-futures
print('requests-futures:')
session = CustomSession()
futures = []
for i in range(10):
futures.append(session.get('http://google.com/', test_id=i))
for future in futures:
try:
r = future.result()
#print((session.timing[i]['cE'] - session.timing[i]['cS']))
except Exception as e:
print(e)
for i in range(10):
print((session.timing[i]['cE'] - session.timing[i]['cS']).total_seconds() * 1000)
# using requests
print('requests:')
for i in range(10):
check_start_timestamp = datetime.utcnow()
r = requests.get('http://google.com')
check_end_timestamp = datetime.utcnow()
cE = int((check_end_timestamp - check_start_timestamp).total_seconds() * 1000)
print(cE)请求-期货:
112.959
118.627
160.139
174.32
214.399
224.295
267.557
276.582
316.824
327.00800000000004请求:
99
104
92
110
100
126
140
112
102
107看来:
requests-futures的响应时间看起来是相加的(时间越来越长)requests运行速度快得多。这是正常的吗?我是不是遗漏了什么会导致这种差异的东西?
发布于 2015-04-23 20:53:07
问题1
请求的响应时间-期货看起来是加性的(时间越来越大)
原因是requests_futures在幕后使用线程池。您可以看到这一点,因为计时发生在块中(为清楚起见添加的分隔符,线程数可以由max_workers参数更改):

如您所见,组的间隔大致相同,这应该是一个请求的响应时间。
理论上,将池大小设置为10为您的测试提供了最佳结果,给出的结果如下:
252.977
168.379
161.689
165.44
169.238
157.929
171.77
154.089
168.283
159.23999999999998然而,下面的效果会产生更多的效果。
问题2
使用普通请求运行得更快。
我不确定,但看看第一批请求的时间,它只有15个单位(微秒?)关了。这可能是由于:
未来的优势是,10次请求的总时间更短,而不是单个的时间,因此这种细微的差异并不是真正值得关注的。
https://stackoverflow.com/questions/29828734
复制相似问题