所以我试图比较threading是更快还是multiprocessing。理论上,由于GIL,多处理应该比多线程更快,因为一次只运行一个线程。但是我得到了相反的结果,即线程比多处理花费的时间更少,我缺少什么请帮忙。下面是线程的代码import threadingfrom queue import Queueimport timeprint_lock = threading.Lock()def exampleJob(worker): time.sleep(10) with print_lock: print(threading.current_thread().name,worker)def threader(): while True: worker = q.get() exampleJob(worker) q.task_done()q = Queue()for x in range(4): t = threading.Thread(target=threader) print(x) t.daemon = True t.start()start = time.time()for worker in range(8): q.put(worker)q.join()print('Entire job took:',time.time() - start)下面是多处理的代码import multiprocessing as mpimport timedef exampleJob(print_lock,worker): # function simulating some computation time.sleep(10) with print_lock: print(mp.current_process().name,worker)def processor(print_lock,q): # function where process pick up the job while True: worker = q.get() if worker is None: # flag to exit the process break exampleJob(print_lock,worker)if __name__ == '__main__': print_lock = mp.Lock() q = mp.Queue() processes = [mp.Process(target=processor,args=(print_lock,q)) for _ in range(4)] for process in processes: process.start() start = time.time() for worker in range(8): q.put(worker) for process in processes: q.put(None) # quit indicator for process in processes: process.join() print('Entire job took:',time.time() - start)
添加回答
举报
0/150
提交
取消