多個request介面的功能最佳化處理速度

Mrwhite86發表於2024-02-15

一、原始程式碼功能如下,包含兩個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秒

 

相關文章