新生代farmer001 2021-04-20 10:19 采纳率: 0%
浏览 42

windows下python多进程/线程创建文件和普通循环创建方法更慢?

如题,刚接触多进程,想比较一下多进程/线程的优势,

于是就在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))
  • 写回答

2条回答 默认 最新

  • Nick Peng 2021-04-20 11:06
    关注

    第14行为什么要用for循环?你的arg直接传元组不就行了

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型