赞
踩
if __name__ == "__main__"
中,否者将报错,这是由于windows系统默认设置spawn,linux直接运行即可,linux默认设置fork,虽然mac支持fork和spawn,但直接运行默认也会报错from multiprocessing import Pool, cpu_count import os import time import threading start_time = time.time() def task(row_list): num_list = [int(row.split(':')[-1]) for row in row_list] result = sum(num_list) print(result) print("------------son result---------------") # 多进程处理 大约7s # def run(): # p = Pool(cpu_count()) # file = open("read.txt", "r", encoding = 'utf-8') # file.readline() # row_list = [] # for line in file: # row_list.append(line.strip()) # if len(row_list) == 1000: # p.apply_async(task, args = (row_list,)) # row_list = [] # if row_list: # p.apply_async(task, args = (row_list,)) # p.close() # p.join() # file.close() # 多线程处理 大约9s def run(): file = open('read.txt', 'r', encoding = 'utf-8') file.readline() row_list = [] for line in file: row_list.append(line.strip()) if len(row_list) == 1000: t = threading.Thread(target = task, args = (row_list,)) t.start() row_list = [] if row_list: t = threading.Thread(target = task, args = (row_list,)) t.start() file.close() if __name__ == "__main__": print(f'主进程id:{os.getpid()}') print("------------------start-------------------") run() print(time.time() - start_time)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。