如题,刚接触多进程,想比较一下多进程/线程的优势,
于是就在windows下创建n个txt文件来比较一下时间,
但是发现普通循环遍历操作的时间最短,这是什么原因?是我多进程、线程使用的有问题吗?
多进程:
def for_mkd(n):
path = "D:\\Pycharm\\workspace\\线程进程相关\\for\\" + str(n) + ".txt"
# print(path)
with open(path, 'w') as fp:
fp.write("0")
def main():
# print("主进程执行中>>> pid={0} time={1}".format(os.getpid(),time.ctime(time.time()) * 1000))
print("主进程执行中>>> pid={0} time={1}".format(os.getpid(),time.time() * 1000))
ps = []
# 创建子进程实例
T1 = time.time() * 1000
for i in range(20000):
p = Process(target=for_mkd,name="mkdir"+str(i),args=(i,))
# ps.append(p)
# 开启进程
p.start()
# print(ps)
# 阻塞进程
# for i in range(2000):
# ps[i].join()
# print("主进程终止")
T2 = time.time() * 1000
print(T2 - T1)
多线程:
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("开始线程:{0},{1}".format(self.name,time.time() * 1000))
mkdir(self.name, self.counter)
print("退出线程:{0},{1}".format(self.name,time.time() * 1000))
def mkdir(threadName, counter):
for i in range(counter):
if exitFlag:
threadName.exit()
path = "D:\\Pycharm\\workspace\\线程进程相关\\thr\\" + str(counter) + ".txt"
with open(path, 'w') as fp:
fp.write("0")
counter -= 1
t1 = time.time() * 1000
# 创建新线程
for i in range(1, 2000):
thread = myThread(i,"Thread" + str(i), i)
# 开启新线程
thread.start()
thread.join(10)
print("退出主线程")
t2 = time.time() * 1000
print("cha is {0}".format(t2 - t1))
普通遍历操作:
def for_mkd(n):
path = "D:\\Pycharm\\workspace\\线程进程相关\\for\\" + str(n) + ".txt"
print(path)
with open(path, 'w') as fp:
fp.write("0")
def main():
t1 = time.time() * 1000
print("begin at {0}".format(time.time() * 1000))
for i in range(20000):
for_mkd(i)
print("end at {0}".format(time.time() * 1000))
t2 = time.time() * 1000
print("cha is {0}".format(t2 - t1))