多个requests接口的功能优化处理速度
一、原始代码功能如下,包含两个request接口的调用,耗时情况约4秒
import datetime
import time
import requests
start_time = datetime.datetime.now()
print("开始时间:",start_time)
url = "http://192.168.37.8:7777/api/mytest2"
data1 = requests.post(url).text
print(data1)
time.sleep(2)
url2 = "http://192.168.37.8:7777/api/mytest"
data2 = requests.get(url2).text
print(data2)
time.sleep(2)
end_time = datetime.datetime.now()
print("结束时间",end_time)
time_need = (end_time - start_time ).seconds
print("耗时豪秒数:",time_need)
耗时约:4秒
二、替换语句,使用session对象,加上session后再调用,优化效果不明显
import datetime
import time
import requests
start_time = datetime.datetime.now()
print("开始时间:",start_time)
session = requests.session()
url = "http://192.168.37.8:7777/api/mytest2"
data1 = session.post(url).text
print(data1)
time.sleep(2)
url2 = "http://192.168.37.8:7777/api/mytest"
data2 = session.get(url2).text
print(data2)
time.sleep(2)
end_time = datetime.datetime.now()
print("结束时间",end_time)
time_need = (end_time - start_time ).seconds
print("耗时豪秒数:",time_need)
耗时依然是:4秒
三、引入多线程机制,优化效果比较明显
1.定义线程方法
def thread_1():
def thread_2():
2.定义线程
thread1 = threading.Thread(target = thread_1)
thread2 = threading.Thread(target = thread_2)
3.启动线程
thread1.start()
thread2.start()
4.等待线程执行完毕
thread1.join()
thread2.join()
其中时间的语句如下:
start_time = datetime.datetime.now()
//
end_time = datetime.datetime.now()
time_need = (end_time - start_time ).seconds
具体的实现如下:
import datetime
import threading
import time
import requests
start_time = datetime.datetime.now()
print("开始时间:",start_time)
def thread_1():
url = "http://192.168.37.8:7777/api/mytest2"
data1 = requests.post(url).text
print(data1)
time.sleep(2)
def thread_2():
url2 = "http://192.168.37.8:7777/api/mytest"
data2 = requests.get(url2).text
print(data2)
time.sleep(2)
thread1 = threading.Thread(target = thread_1)
thread2 = threading.Thread(target = thread_2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
end_time = datetime.datetime.now()
print("结束时间",end_time)
time_need = (end_time - start_time ).seconds
print("耗时豪秒数:",time_need)
耗时确实下降至2秒