建立一个测试模块:
#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