Python中发出请求的多处理
我想测试网站的响应速度,所以我这样写:Python中发出请求的多处理,python,Python,我想测试网站的响应速度,所以我这样写: import urllib.request as request import time from multiprocessing import Process, Lock, Value def response_test(lock, count, time1, time2): t1 = time.time() r = request.urlopen('http://localhost/json/threads') t2 = ti
import urllib.request as request
import time
from multiprocessing import Process, Lock, Value
def response_test(lock, count, time1, time2):
t1 = time.time()
r = request.urlopen('http://localhost/json/threads')
t2 = time.time()
c = r.read()
t3 = time.time()
lock.acquire()
try:
time1.value += t2-t1
time2.value += t3-t2
count.value += 1
if count.value == 4:
print(time1.value / 4, time2.value / 4)
finally:
lock.release()
if __name__ == '__main__':
lock = Lock()
count = Value('i', 0)
time1 = Value('d', 0.0)
time2 = Value('d', 0.0)
for i in range(4):
p = Process(target=response_test, args=(lock,count,time1,time2))
p.start()
输出:0.5701152682304382 0.015613257884979248
所以看起来需要0.5秒才能得到响应。但是没有多处理
,只有一个简单的循环:
def response_test():
t1 = time.time()
r = request.urlopen('http://localhost/json/threads')
t2 = time.time()
c = r.read()
t3 = time.time()
return (t2-t1, t3-t2)
重复同样的次数并计算平均值,我得到了
0.18742609024047852,0.01562190055847168
。为什么使用多处理
速度较慢?您是否多次运行这两个测试以考虑随机性?您使用的任何服务器是否可能在队列中一次只处理一个请求?@MattiVirkkunen谢谢!我想我使用的开发服务器不支持多进程或多线程。在这种情况下,如果您几乎在同一时刻发出多个请求,那么总共需要更长的时间,因为服务器正在处理另一个进程请求时,某些进程将等待。当4个请求同时出现时,可能测试工作正常,而您的web服务器执行较慢?如果同时有4个请求,速度应该至少慢2倍,这与您的数字接近。您是否多次运行这两个测试以考虑随机性?您使用的任何服务器是否可能在队列中一次只处理一个请求?@MattiVirkkunen谢谢!我想我使用的开发服务器不支持多进程或多线程。在这种情况下,如果您几乎在同一时刻发出多个请求,那么总共需要更长的时间,因为服务器正在处理另一个进程请求时,某些进程将等待。当4个请求同时出现时,可能测试工作正常,而您的web服务器执行较慢?如果同时有4个请求,速度应该至少慢2倍,这与您的数字显示的速度接近。