Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6373961
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T01:25:47+00:00 2026-05-25T01:25:47+00:00

So I’ve been messing around with python’s multiprocessing lib for the last few days

  • 0

So I’ve been messing around with python’s multiprocessing lib for the last few days and I really like the processing pool. It’s easy to implement and I can visualize a lot of uses. I’ve done a couple of projects I’ve heard about before to familiarize myself with it and recently finished a program that brute forces games of hangman.

Anywho, I was doing an execution time compairison of summing all the prime numbers between 1 million and 2 million both single threaded and through a processing pool. Now, for the hangman cruncher, putting the games in a processing pool improved execution time by about 8 times (i7 with 8 cores), but when grinding out these primes, it actually increased processing time by almost a factor of 4.

Can anyone tell me why this is? Here is the code for anyone interested in looking at or testing it:

#!/user/bin/python.exe
import math
from multiprocessing import Pool

global primes
primes = []

def log(result):
    global primes

    if result:
        primes.append(result[1])

def isPrime( n ):
    if n < 2:
        return False
    if n == 2:
        return True, n

    max = int(math.ceil(math.sqrt(n)))
    i = 2
    while i <= max:
        if n % i == 0:
            return False
        i += 1
    return True, n


def main():

   global primes

   #pool = Pool()

   for i in range(1000000, 2000000):
       #pool.apply_async(isPrime,(i,), callback = log)
       temp = isPrime(i)
       log(temp)

   #pool.close()
   #pool.join()

   print sum(primes)

   return

if __name__ == "__main__":
    main()

It’ll currently run in a single thread, to run through the processing pool, uncomment the pool statements and comment out the other lines in the main for loop.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T01:25:47+00:00Added an answer on May 25, 2026 at 1:25 am

    the most efficient way to use multiprocessing is to divide the work into n equal sized chunks, with n the size of the pool, which should be approximately the number of cores on your system. The reason for this is that the work of starting subprocesses and communicating between them is quite large. If the size of the work is small compared to the number of work chunks, then the overhead of IPC becomes significant.

    In your case, you’re asking multiprocessing to process each prime individually. A better way to deal with the problem is to pass each worker a range of values, (probably just a start and end value) and have it return all of the primes in that range it found.

    In the case of identifying large-ish primes, the work done grows with the starting value, and so You probably don’t want to divide the total range into exactly n chunks, but rather n*k equal chunks, with k some reasonable, small number, say 10 – 100. that way, when some workers finish before others, there’s more work left to do and it can be balanced efficiently across all workers.

    Edit: Here’s an improved example to show what that solution might look like. I’ve changed as little as possible so you can compare apples to apples.

    #!/user/bin/python.exe
    import math
    from multiprocessing import Pool
    
    global primes
    primes = set()
    
    def log(result):
        global primes
    
        if result:
            # since the result is a batch of primes, we have to use 
            # update instead of add (or for a list, extend instead of append)
            primes.update(result)
    
    def isPrime( n ):
        if n < 2:
            return False
        if n == 2:
            return True, n
    
        max = int(math.ceil(math.sqrt(n)))
        i = 2
        while i <= max:
            if n % i == 0:
                return False
            i += 1
        return True, n
    
    def isPrimeWorker(start, stop):
        """
        find a batch of primes
        """
        primes = set()
        for i in xrange(start, stop):
            if isPrime(i):
                primes.add(i)
    
        return primes
    
    
    
    def main():
    
        global primes
    
        pool = Pool()
    
        # pick an arbitrary chunk size, this will give us 100 different 
        # chunks, but another value might be optimal
        step = 10000
    
        # use xrange instead of range, we don't actually need a list, just
        # the values in that range.
        for i in xrange(1000000, 2000000, step):
            # call the *worker* function with start and stop values.
            pool.apply_async(isPrimeWorker,(i, i+step,), callback = log)
    
        pool.close()
        pool.join()
    
        print sum(primes)
    
        return
    
    if __name__ == "__main__":
        main()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a jquery bug and I've been looking for hours now, I can't
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I would like to count the length of a string with PHP. The string
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have some data like this: 1 2 3 4 5 9 2 6
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.