I recently started experimenting with multiprocessing to speed up a task. I created a script that does fuzzy string matching and calculates scores using different algorithms (I wanted to compare different matching techniques). You can find the full source here: https://bitbucket.org/bergonzzi/fuzzy-compare/src. As input it takes 2 files which are combined into pairs (each line of file1 with each line of file2). For each pair, fuzzy match scores are calculated.
I made 3 versions. Running with the sample data provided in my repo (which consists of 697.340 items after being combined into pairs), I have the following timings:
- Simple single process - 0:00:47
- Multiprocess using Pool.map() - 0:00:13
- Multiprocess using Queues (producer/consumer pattern) - 0:01:04
I'm trying to understand why my Pool.map() version is much faster than my Queue version, which is actually slower than the simple single-process one.
My reasoning for even attempting to using Queues is that the Pool.map() version holds on to the results until everything's finished and only writes to a file at the end. This means that for big files it ends up eating a lot of memory. I'm talking about this version (linking to it because it's a lot of code to paste here).
To solve this I refactored it into a producer/consumer pattern (or attempted at least). Here I first produce jobs by combining both input files and put them in a queue which the consumers process (calculate fuzzy match scores). Done jobs are put into an out queue. Then I have a single process grabbing done items from this queue and writing them to a file. This way, in theory, I wouldn't need as much memory since results would be flushed out to disk. It seems to work fine but it's much slower. I also noticed that the 4 processes I'm spawning don't seem to use up 100% CPU when looking at the Activity Monitor on Mac OSX (which is not the case with the Pool.map() version).
Another thing I notice is that my producer function seems to fill up the queue properly but the consumer processes seem to wait until the queue is filled up instead of starting to work as soon as the first item arrives. I'm probably doing something wrong there...
For reference here's some of the relevant code for the Queue version (although it's better to look at the full code in the repo linked above).
Here's my producer function:
def combine(list1, list2):
'''
Combine every item of list1 with every item of list 2,
normalize put the pair in the job queue.
'''
pname = multiprocessing.current_process().name
for x in list1:
for y in list2:
# slugify is a function to normalize the strings
term1 = slugify(x.strip(), separator=' ')
term2 = slugify(y.strip(), separator=' ')
job_queue.put_nowait([term1, term2])
This is the writer function:
def writer(writer_queue):
out = open(file_out, 'wb')
pname = multiprocessing.current_process().name
out.write(header)
for match in iter(writer_queue.get, "STOP"):
print("%s is writing %s") % (pname, str(match))
line = str(';'.join(match) + '\n')
out.write(line)
out.close()
This is the worker function that does the actual calculations (stripped out most of the code since it doesn't make a difference here, full source on the repo):
def score_it(job_queue, writer_queue):
'''Calculate scores for pair of words.'''
pname = multiprocessing.current_process().name
for pair in iter(job_queue.get_nowait, "STOP"):
# do all the calculations and put the result into the writer queue
writer_queue.put(result)
This is how I set up the processes:
# Files
to_match = open(args.file_to_match).readlines()
source_list = open(args.file_to_be_matched).readlines()
workers = 4
job_queue = multiprocessing.Manager().Queue()
writer_queue = multiprocessing.Manager().Queue()
processes = []
print('Start matching with "%s", minimum score of %s and %s workers') % (
args.algorithm, minscore, workers)
# Fill up job queue
print("Filling up job queue with term pairs...")
c = multiprocessing.Process(target=combine, name="Feeder", args=(to_match, source_list))
c.start()
c.join()
print("Job queue size: %s") % job_queue.qsize()
# Start writer process
w = multiprocessing.Process(target=writer, name="Writer", args=(writer_queue,))
w.start()
for w in xrange(workers):
p = multiprocessing.Process(target=score_it, args=(job_queue, writer_queue))
p.start()
processes.append(p)
job_queue.put("STOP")
for p in processes:
p.join()
writer_queue.put("STOP")
I've read quite a bit here about multiprocessing being slower sometimes and I know this has to do with the overhead of creating and managing new processes. Also when the job to be done isn't "big" enough, the effect of multiprocessing might not be visible. However in this case I think the job's quite big and also the Pool.map() version seems to prove it because it's much faster.
Am I doing something really wrong when managing all these processes and passing over queue objects? How can this be optimised so that results can be written to a file as they are processed in order to minimise the amount of memory required while running it?
Thanks!
poolbased version, you might try usingpool.imapto get an iterator yielding the result values as they are computed by the worker processes. In yourmapcode, just swapimapin formapand move thepool.closeandpool.joincalls below the loop that writes out the results and you may be set! - Blckknghtchunksizeparameter. If I understand things correctly,mapuses larger chunks by default thanimapdoes, which can greatly reduce the overhead if the sequence to be mapped over is very long. - Blckknghtchunksize=1to say,chunksize=100), but the overhead should continue to get less the larger you make it. Themapmethod computes a default chunksize that is equivalent tomath.ceil(len(iterable) / 4.0 / cpu_count())), so that could be a place to start withimaptoo. - Blckknght