我做了一些测试,这很有趣,哈哈。我认为这不是很有效:) 也许还有另一种有效的方法?
import time
import multiprocessing
## Generate sample big file (~158Mo, 2M lines)
import random
chunks = "Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua".split()
with open(r"D:\testbig.txt", "w", encoding="utf-8") as f:
for i in range(2000000):
for nch in range(random.randrange(5,20)):
f.write(random.choice(chunks))
f.write(" ")
f.write("\n")
# Proposed direct way
fileName = "foo"
time_start = time.time()
myList = []
# mySet = set()
with open(r"D:\testbig.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
time_end = time.time()
print(fileName, ": loaded ", round(time_end-time_start, 4)," seconds" )
for line in lines:
content = line.split()
myList.append(content)
time_end = time.time()
print(fileName, ": ", len(myList), " rows loaded in", round(time_end-time_start, 4)," seconds")
del myList
# Results:
## foo : loaded 0.9204 seconds
## foo : 2000000 rows loaded in 6.9107 seconds
## Press any key to continue . . .
# Workers method:
MAXPROCESS = 7
CHUNKLEN = 25600000
# The worker
def splitter(lines):
myList = []
for line in lines:
content = line.split()
myList.append(content)
return myList
# The code has to be fully loaded, therefore in a function
def main():
fileName = "foo"
time_start = time.time()
# Declare a pool of workers
pool = multiprocessing.Pool(MAXPROCESS)
results = []
with open(r"D:\testbig.txt", "r", encoding="utf-8") as f:
while True:
# Read an amount of lines (about CHUNKLEN bytes)
lines = f.readlines(CHUNKLEN)
# End of file breaks the loop
if len(lines) == 0: break
# Queue data to be processed
results.append(pool.apply_async(splitter, (lines,)))
time_end = time.time()
print(fileName, ": loaded ", round(time_end-time_start, 4)," seconds" )
# Wait for queue to be processed
pool.close()
pool.join()
# Put list pieces together
myList = []
for result in results:
myList += result.get()
time_end = time.time()
print(fileName, ": ", len(myList), " rows loaded in", round(time_end-time_start, 4)," seconds")
main()
# Results:
# MAXPROCESS = 4
# CHUNKLEN = 8192
## foo : loaded 5.0075 seconds
## foo : 2000000 rows loaded in 11.0446 seconds
## Press any key to continue . . .
# MAXPROCESS = 7
# CHUNKLEN = 25600
## foo : loaded 6.0839 seconds
## foo : 2000000 rows loaded in 9.1102 seconds
## Press any key to continue . . .
# MAXPROCESS = 7
# CHUNKLEN = 25600000
## foo : loaded 3.1199 seconds
## foo : 2000000 rows loaded in 11.7622 seconds
## Press any key to continue . . .