I am trying to split a large file into smaller pieces. I will read all the data from the large file first and then use multiprocessing to write them to different smaller data file.
Here is method one, where is use multiprocessing.Process to initialize a process, which works well
def split_data_with_process(filepath, chunk_num):
def write(write_data, index, name, prev_path, suffix):
print("enter")
start_time = time.time()
with open(prev_path + f"/{name}_{index}.{suffix}", "w", encoding="utf-8") as f:
f.writelines(write_data)
print(time.time()-start_time)
prev_path, filename = filepath.rsplit("/", maxsplit=1)
name, suffix = filename.split(".")
with open(filepath, "r", encoding="utf-8") as f:
totalList = f.readlines()
chunksize = math.ceil(len(totalList) / chunk_num)
data = [(totalList[start:start + chunksize], index) for index, start in
enumerate(range(0, len(totalList), chunksize))]
tasks = []
start_time = time.time()
for each in data:
task = multiprocessing.Process(target=write, args=(each[0], each[1], name, prev_path, suffix))
task.start()
tasks.append(task)
for each in tasks:
each.join()
end_time = time.time()
print(end_time - start_time)
and the output is
enter
enter
enter
enter
enter
7.192562818527222
8.827389001846313
9.067991018295288
9.476916313171387
7.729929208755493
15.109729290008545
then I try to rewrite the code with ProcessPoolExecutor, and the code is like
def write(input):
list, index, prev_path, name, suffix = input
print("enter")
start_time = time.time()
with open(prev_path + f"/{name}_{index}.{suffix}", "w", encoding="utf-8") as f:
f.writelines(list)
print(time.time() - start_time)
return len(list)
def split_data_with_process_2(filepath, chunk_num):
prev_path, filename = filepath.rsplit("/", maxsplit=1)
name, suffix = filename.split(".")
with open(filepath, "r", encoding="utf-8") as f:
totalList = f.readlines()
chunksize = math.ceil(len(totalList) / chunk_num)
data = [(totalList[start:start + chunksize], index, prev_path, name, suffix) for index, start in
enumerate(range(0, len(totalList), chunksize))]
start_time = time.time()
with ProcessPoolExecutor(max_workers=chunk_num) as pool:
result = pool.map(write, data)
print(sum(result))
end_time = time.time()
print(end_time - start_time)
In second way it will take a much longer time then the first way. I find that it looks like that different processes are working serially instead of working parallel. and the output is
enter
3.416102170944214
enter
3.3221476078033447
enter
3.198657989501953
enter
3.453885316848755
enter
3.261833429336548
16149274
42.55615472793579
So what is the problem here?