原因:
1、如果原接口是使用的6进程(线程),那么6线程调用一般是最快的,为啥?
因为存在上下文切换。所以10进程的时间浪费在上下文切换上面了。
2、上下文切换都需要切换哪些数据?
看代码,不就是一个函数吗,有啥好切换的? --------大错特错
切换的内容如下:
-
CPU寄存器:
- 包括通用寄存器、指令指针、堆栈指针等,这些寄存器存储了当前执行线程的状态和上下文。
-
线程/进程状态:
- 包括当前线程或进程的状态(如运行、就绪、阻塞等),操作系统需要知道每个线程的状态以正确调度。
-
内存管理信息:
- 包括页表、段表等内存管理结构,涉及到线程或进程的内存空间和分配。
-
调度信息:
- 包括优先级、时间片等信息,以决定哪个线程或进程应该在下一次调度中运行。
-
I/O状态:
- 如果线程或进程在等待I/O操作(如文件读取、网络请求等),相关的I/O状态和信息也需要保存。
-
其他资源:
- 包括打开的文件描述符、网络连接等资源的状态信息。
3、示例代码
import os
import requests
import time
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor, as_completed# 开始计时
start_time = time.time()# 设置URL
url = "http://192.168.190.67:8824/IS-CV/feature/image/file"# 文件夹路径
folder_path = '/home/lh123/lh/Image_interface_test_9_18/data_test/iamge/'# 定义上传文件的函数
def upload_file(filename):file_path = os.path.join(folder_path, filename)if os.path.isfile(file_path):with open(file_path, 'rb') as file:files = [('file', (filename, file, 'image/jpeg'))]headers = {}response = requests.post(url, headers=headers, files=files)return filename, response.textreturn filename, None# 获取文件列表
file_list = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]# 使用6个线程进行文件上传
num = len(file_list)
responses = []with ThreadPoolExecutor(max_workers=12) as executor:future_to_file = {executor.submit(upload_file, filename): filename for filename in file_list}print(future_to_file)for future in tqdm(as_completed(future_to_file), total=num):filename = future_to_file[future]try:result = future.result()responses.append(result)# 如果需要,可以打印响应# print(f"Response for {filename}: {result[1]}")except Exception as exc:print(f"{filename} generated an exception: {exc}")# 结束计时
end_time = time.time()
execution_time = end_time - start_time
print(f"时间: {execution_time:.2f} 秒")
print("图片数量", num)
print("速度(秒/张)", execution_time / num)