欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 10线程调用接口为啥比6进程调用接口慢?

10线程调用接口为啥比6进程调用接口慢?

2025/2/1 18:01:05 来源:https://blog.csdn.net/qq_43808611/article/details/142362763  浏览:    关键词:10线程调用接口为啥比6进程调用接口慢?

原因:
1、如果原接口是使用的6进程(线程),那么6线程调用一般是最快的,为啥?
因为存在上下文切换。所以10进程的时间浪费在上下文切换上面了。
2、上下文切换都需要切换哪些数据?
看代码,不就是一个函数吗,有啥好切换的? --------大错特错

切换的内容如下:

  1. CPU寄存器

    • 包括通用寄存器、指令指针、堆栈指针等,这些寄存器存储了当前执行线程的状态和上下文。
  2. 线程/进程状态

    • 包括当前线程或进程的状态(如运行、就绪、阻塞等),操作系统需要知道每个线程的状态以正确调度。
  3. 内存管理信息

    • 包括页表、段表等内存管理结构,涉及到线程或进程的内存空间和分配。
  4. 调度信息

    • 包括优先级、时间片等信息,以决定哪个线程或进程应该在下一次调度中运行。
  5. I/O状态

    • 如果线程或进程在等待I/O操作(如文件读取、网络请求等),相关的I/O状态和信息也需要保存。
  6. 其他资源

    • 包括打开的文件描述符、网络连接等资源的状态信息。

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)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com