如何在Python中正确模拟CPU密集型长耗时函数?
正确模拟Python中CPU密集型长耗时任务的方法
你之前用time.sleep(5)模拟CPU密集型任务是错误的,因为time.sleep属于IO阻塞操作,执行时会主动释放GIL(全局解释器锁),多个线程可以同时进入休眠状态,最终总耗时和单个任务差不多,体现不出GIL对CPU密集型任务的限制。
要正确模拟CPU密集型任务,需要编写持续占用CPU执行计算的代码,这类操作不会释放GIL,线程池中的多个任务只能交替执行,总耗时会接近单个任务耗时的倍数。
以下是符合要求的实现示例:
import time from datetime import datetime def cpu_bound_task(): start_time = datetime.now() print(f"Started at {start_time}") # 控制任务运行约5秒,通过密集计算占用CPU target_end = start_time.timestamp() + 5 while time.time() < target_end: # 执行无意义但消耗CPU的运算(比如大整数幂运算) _ = 2 ** 1000000 finish_time = datetime.now() print(f"Executed at {finish_time}")
用线程池测试的代码:
import concurrent.futures with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor: executor.submit(cpu_bound_task) executor.submit(cpu_bound_task)
运行这段代码后,总耗时会接近10秒——因为GIL的存在,两个CPU密集型线程无法真正并行,只能交替占用CPU资源,最终总耗时是单个任务耗时的近似两倍。
如果用多进程池ProcessPoolExecutor测试,总耗时会接近5秒,因为多进程不受GIL限制,能真正并行执行CPU密集型任务。
内容的提问来源于stack exchange,提问作者StuffHappens
相关产品推荐
相关产品推荐

