# comp_cpu.pyimporttimefromthreadingimportThreadfrommultiprocessingimportPoolCOUNT=600000defcount_cpu(n):whilen>0:n-=1start=time.time()count_cpu(COUNT)end=time.time()print("Single threads:\n Time taken in seconds -",end-start)t1=Thread(target=count_cpu,args=(COUNT//2,))t2=Thread(target=count_cpu,args=(COUNT//2,))# t1 = Thread(target=count_cpu, args=(COUNT,))# t2 = Thread(target=count_cpu, args=(COUNT,))start=time.time()t1.start()t2.start()t2.join()end=time.time()print("Two threads:\n Time taken in seconds -",end-start)pool=Pool(processes=2)start=time.time()r1=pool.apply_async(count_cpu,[COUNT//2])r2=pool.apply_async(count_cpu,[COUNT//2])pool.close()pool.join()end=time.time()print("Two processes:\n Time taken in seconds -",end-start)
结果
1
2
3
4
5
6
Single threads:
Time taken in seconds - 0.030620098114013672
Two threads:
Time taken in seconds - 0.03354072570800781
Two processes:
Time taken in seconds - 0.019550323486328125
# comp_io.pyimporttimefromthreadingimportThreadfrommultiprocessingimportPoolCOUNT=6000defcount_io(n):whilen>0:time.sleep(0.001)n-=1start=time.time()count_io(COUNT)end=time.time()print("Single threads:\n Time taken in seconds -",end-start)t1=Thread(target=count_io,args=(COUNT//2,))t2=Thread(target=count_io,args=(COUNT//2,))# t1 = Thread(target=count_io, args=(COUNT,))# t2 = Thread(target=count_io, args=(COUNT,))start=time.time()t1.start()t2.start()t2.join()end=time.time()print("Two threads:\n Time taken in seconds -",end-start)pool=Pool(processes=2)start=time.time()r1=pool.apply_async(count_io,[COUNT//2])r2=pool.apply_async(count_io,[COUNT//2])pool.close()pool.join()end=time.time()print("Two processes:\n Time taken in seconds -",end-start)
结果
1
2
3
4
5
6
Single threads:
Time taken in seconds - 6.363478899002075
Two threads:
Time taken in seconds - 3.1789000034332275
Two processes:
Time taken in seconds - 3.1876704692840576