测试  多进程  多线程  单进程执行相同的IO操作和CPU操作的事件

建立一个测试模块:

#test.py
#计算密集
def count(x,y):
    c = 0
    while c < 7000000:
        x += 1
        y += 1
        c += 1

#io密集
def write():
    f = open("test.txt",'w')
    for x in range(2000000):
        f.write("hello world\n")
    f.close()

def read():
    f = open("test.txt")
    lines = f.readlines()
    f.close()

单进程程序运算时间:

#单进程程序
from test import *
import time 

# t = time.time()
# for i in range(10):
#     count(1,1)
# print("Line cpu:",time.time() - t)


#IO运算
t = time.time()
for i in range(10):
    write()
    read()
print("Line IO:",time.time() - t)

多线程cpu运算时间:

from test import * 
import threading 
import time 

counts = []

t = time.time()

for x in range(10):
    th = threading.Thread(target = count,args = (1,1))
    th.start()
    counts.append(th)

for i in counts:
    i.join()
print("Thread cpu",time.time() - t)

多线程IO运算时间:

from test import * 
import threading 
import time 

counts = []

def io():
    write()
    read()

t = time.time()

for x in range(10):
    th = threading.Thread(target = io)
    th.start()
    counts.append(th)

for i in counts:
    i.join()
print("Thread IO",time.time() - t)

 

多进程cpu运算时间:

from test import * 
import multiprocessing 
import time 

counts = []

t = time.time()

for x in range(10):
    th = multiprocessing.Process\
    (target = count,args = (1,1))
    th.start()
    counts.append(th)

for i in counts:
    i.join()
print("Process cpu",time.time() - t)

多进程IO运算时间:

from test import * 
import multiprocessing 
import time 

counts = []

def io():
    write()
    read()

t = time.time()

for x in range(10):
    th = multiprocessing.Process(target = io)
    th.start()
    counts.append(th)

for i in counts:
    i.join()
print("Process IO",time.time() - t)

运算时间:

  • Line cpu: 8.15166711807251

  • Line IO: 6.841825246810913

  • Thread cpu 8.414522647857666

  • Thread IO 6.023292541503906

  • Process cpu 4.079084157943726

  • Process IO 3.2132551670074463

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值