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.text
    return 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值