Speed up this code?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • aomighty@gmail.com

    #1

    Speed up this code?

    I'm creating a program to calculate all primes numbers in a range of 0
    to n, where n is whatever the user wants it to be. I've worked out the
    algorithm and it works perfectly and is pretty fast, but the one thing
    seriously slowing down the program is the following code:

    def rmlist(original , deletions):
    return [i for i in original if i not in deletions]

    original will be a list of odd numbers and deletions will be numbers
    that are not prime, thus this code will return all items in original
    that are not in deletions. For n > 100,000 or so, the program takes a
    very long time to run, whereas it's fine for numbers up to 10,000.

    Does anybody know a faster way to do this? (finding the difference all
    items in list a that are not in list b)?

    Thanks,
    Martin

  • Ben Cartwright

    #2
    Re: Speed up this code?

    aomighty@gmail. com wrote:[color=blue]
    > I'm creating a program to calculate all primes numbers in a range of 0
    > to n, where n is whatever the user wants it to be. I've worked out the
    > algorithm and it works perfectly and is pretty fast, but the one thing
    > seriously slowing down the program is the following code:
    >
    > def rmlist(original , deletions):
    > return [i for i in original if i not in deletions]
    >
    > original will be a list of odd numbers and deletions will be numbers
    > that are not prime, thus this code will return all items in original
    > that are not in deletions. For n > 100,000 or so, the program takes a
    > very long time to run, whereas it's fine for numbers up to 10,000.
    >
    > Does anybody know a faster way to do this? (finding the difference all
    > items in list a that are not in list b)?[/color]

    The "in" operator is expensive for lists because Python has to check,
    on average, half the items in the list. Use a better data structure...
    in this case, a set will do nicely. See the docs:




    Oh, and you didn't ask for it, but I'm sure you're going to get a dozen
    pet implementations of prime generators from other c.l.py'ers. So
    here's mine. :-)

    def primes():
    """Generate prime numbers using the sieve of Eratosthenes."" "
    yield 2
    marks = {}
    cur = 3
    while True:
    skip = marks.pop(cur, None)
    if skip is None:
    # unmarked number must be prime
    yield cur
    # mark ahead
    marks[cur*cur] = 2*cur
    else:
    n = cur + skip
    while n in marks:
    # x already marked as multiple of another prime
    n += skip
    # first unmarked multiple of this prime
    marks[n] = skip
    cur += 2

    --Ben

    Comment

    • Tim Chase

      #3
      Re: Speed up this code?

      > def rmlist(original , deletions):[color=blue]
      > return [i for i in original if i not in deletions]
      >
      > original will be a list of odd numbers and deletions will be numbers
      > that are not prime, thus this code will return all items in original
      > that are not in deletions. For n > 100,000 or so, the program takes a
      > very long time to run, whereas it's fine for numbers up to 10,000.
      >
      > Does anybody know a faster way to do this? (finding the difference all
      > items in list a that are not in list b)?[/color]

      Testing for membership in an unsorted list is an O(n) sort of
      operation...the larger the list, the longer it takes.

      I presume order doesn't matter, or that the results can be sorted
      after the fact. If this is the case, it's quite efficient to use
      sets which provide intersection/difference/union methods. If you
      pass in sets rather than lists, you can simply

      return original.differ ence(deletions)

      It's almost not worth calling a function for :) There's also an
      in-place version called difference_upda te().

      Once you've found all the results you want, and done all the set
      differences you want, you can just pass the resulting set to a
      list and sort it, if sorted results matter.

      -tkc




      Comment

      • Paul Rubin

        #4
        Re: Speed up this code?

        aomighty@gmail. com writes:[color=blue]
        > Does anybody know a faster way to do this? (finding the difference all
        > items in list a that are not in list b)?[/color]
        [color=blue][color=green][color=darkred]
        >>> a = [3, 7, 16, 1, 2, 19, 13, 4, 0, 8] # random.sample(r ange(20),10)
        >>> b = [15, 11, 7, 2, 0, 3, 9, 1, 12, 16] # similar
        >>> sorted(set(a)-set(b))
        >>> [4, 8, 13, 19][/color][/color][/color]

        but you probably don't want to use that kind of implementation.

        Here's a version using generators:

        def sieve_all(n = 100):
        # yield all primes up to n
        stream = iter(xrange(2, n))
        while True:
        p = stream.next()
        yield p
        def s1(p, stream):
        # yield all non-multiple of p
        return (q for q in stream if q%p != 0)
        stream = s1(p, stream)

        # print all primes up to 100
        print list(sieve_all( 100))

        It's cute, but horrendous once you realize what it's doing ;-)

        Comment

        • aomighty@gmail.com

          #5
          Re: Speed up this code?

          I got it working using difference() and sets, thanks all! 100,000 takes
          about 3 times the time of 10,000, which is what my math buddies told me
          I should be getting, rather than an exponential increase :). Thanks,
          all!

          Comment

          • Kent Johnson

            #6
            Re: Speed up this code?

            aomighty@gmail. com wrote:[color=blue]
            > I'm creating a program to calculate all primes numbers in a range of 0
            > to n, where n is whatever the user wants it to be. I've worked out the
            > algorithm and it works perfectly and is pretty fast, but the one thing
            > seriously slowing down the program is the following code:
            >
            > def rmlist(original , deletions):
            > return [i for i in original if i not in deletions]
            >
            > original will be a list of odd numbers and deletions will be numbers
            > that are not prime, thus this code will return all items in original
            > that are not in deletions. For n > 100,000 or so, the program takes a
            > very long time to run, whereas it's fine for numbers up to 10,000.
            >
            > Does anybody know a faster way to do this? (finding the difference all
            > items in list a that are not in list b)?[/color]

            - Make deletions a set, testing for membership in a set is much faster
            than searching a large list.

            - Find a better algorithm ;)

            Kent

            Comment

            • bearophileHUGS@lycos.com

              #7
              Re: Speed up this code?

              If you are interested in such programs, you can take a look at this one
              too:


              It requires more memory, but it's quite fast.

              Bye,
              bearophile

              Comment

              • Frank Millman

                #8
                Re: Speed up this code?


                bearophileHUGS@ lycos.com wrote:[color=blue]
                > If you are interested in such programs, you can take a look at this one
                > too:
                > http://aspn.activestate.com/ASPN/Coo.../Recipe/366178
                >
                > It requires more memory, but it's quite fast.
                >
                > Bye,
                > bearophile[/color]

                I compared the speed of this one (A) with the speed of Paul Rubin's
                above (B).

                Primes from 1 to 100 -
                A - 0.000118
                B - 0.000007

                Primes from 1 to 200 -
                A - 0.000224
                B - 0.000008

                Primes from 1 to 300 -
                A - 0.000278
                B - 0.000008

                Nice one, Paul.

                Frank Millman

                Comment

                • Gregory Petrosyan

                  #9
                  Re: Speed up this code?

                  # Paul Rubin's version
                  gregory@home:~$ python -mtimeit "import test2" "test2.primes(1 000)"
                  100 loops, best of 3: 14.3 msec per loop

                  # version from the Cookbook
                  gregory@home:~$ python -mtimeit "import test1" "test1.primes(1 000)"
                  1000 loops, best of 3: 528 usec per loop

                  Comment

                  • John Machin

                    #10
                    Re: Speed up this code?

                    On 26/05/2006 11:25 PM, Frank Millman wrote:[color=blue]
                    > bearophileHUGS@ lycos.com wrote:[color=green]
                    >> If you are interested in such programs, you can take a look at this one
                    >> too:
                    >> http://aspn.activestate.com/ASPN/Coo.../Recipe/366178
                    >>
                    >> It requires more memory, but it's quite fast.
                    >>
                    >> Bye,
                    >> bearophile[/color]
                    >
                    > I compared the speed of this one (A) with the speed of Paul Rubin's
                    > above (B).
                    >
                    > Primes from 1 to 100 -
                    > A - 0.000118
                    > B - 0.000007
                    >
                    > Primes from 1 to 200 -
                    > A - 0.000224
                    > B - 0.000008
                    >
                    > Primes from 1 to 300 -
                    > A - 0.000278
                    > B - 0.000008
                    >
                    > Nice one, Paul.
                    >
                    > Frank Millman
                    >[/color]

                    Nice one, Frank.

                    Go back and read Paul's code. Read what he wrote at the bottom: """It's
                    cute, but horrendous once you realize what it's doing ;-) """
                    Pax Heisenberg, it is innately horrendous, whether observers realise it
                    or not :-)

                    Comment

                    • bearophileHUGS@lycos.com

                      #11
                      Re: Speed up this code?

                      I have tried this comparison, with a version I've modified a bit, I
                      have encoutered a problem in sieve_all, for example with n=10000, I
                      don't know why:

                      def sieve_all(n=100 ):
                      # yield all primes up to n
                      stream = iter(xrange(2, n))
                      while True:
                      p = stream.next()
                      yield p
                      def s1(p, stream):
                      # yield all non-multiple of p
                      return (q for q in stream if q%p != 0)
                      stream = s1(p, stream)


                      def primes(n):
                      "primes(n): return a list of prime numbers <=n."
                      # Recipe 366178 modified and fixed
                      if n == 2:
                      return [2]
                      elif n<2:
                      return []
                      s = range(3, n+2, 2)
                      mroot = n ** 0.5
                      half = len(s)
                      i = 0
                      m = 3
                      while m <= mroot:
                      if s[i]:
                      j = (m*m - 3) / 2
                      s[j] = 0
                      while j < half:
                      s[j] = 0
                      j += m
                      i += 1
                      m = 2 * i + 3
                      if s[-1] > n:
                      s[-1] = 0
                      return [2] + filter(None, s)



                      from time import clock
                      pmax = 21

                      for p in xrange(12, pmax):
                      n = 2 ** p
                      t1 = clock()
                      primes(n)
                      t2 = clock()
                      list(sieve_all( n))
                      t3 = clock()
                      print "primes(2^% s= %s):" % (p, n), round(t2-t1, 3), "s",
                      round(t3-t2, 3), "s"

                      import psyco
                      psyco.bind(prim es)
                      psyco.bind(siev e_all)

                      for p in xrange(12, pmax):
                      n = 2 ** p
                      t1 = clock()
                      primes(n)
                      t2 = clock()
                      list(sieve_all( n))
                      t3 = clock()
                      print "primes(2^% s= %s):" % (p, n), round(t2-t1, 3), "s",
                      round(t3-t2, 3), "s"


                      Bye,
                      bearophile

                      Comment

                      • John Machin

                        #12
                        Re: Speed up this code?

                        On 27/05/2006 6:57 AM, bearophileHUGS@ lycos.com wrote:[color=blue]
                        > I have tried this comparison, with a version I've modified a bit, I
                        > have encoutered a problem in sieve_all, for example with n=10000, I
                        > don't know why:[/color]

                        It might have been better use of bandwidth to give details of the
                        problem instead of all that extraneous source code.

                        Did you get this: """RuntimeError : maximum recursion depth exceeded"""?

                        You don't know why?

                        Comment

                        • Frank Millman

                          #13
                          Re: Speed up this code?


                          Gregory Petrosyan wrote:[color=blue]
                          > # Paul Rubin's version
                          > gregory@home:~$ python -mtimeit "import test2" "test2.primes(1 000)"
                          > 100 loops, best of 3: 14.3 msec per loop
                          >
                          > # version from the Cookbook
                          > gregory@home:~$ python -mtimeit "import test1" "test1.primes(1 000)"
                          > 1000 loops, best of 3: 528 usec per loop[/color]

                          You are quite right, Gregory, my timings are way off.

                          I have figured out my mistake. Paul's function is a generator. Unlike a
                          normal function, when you call a generator function, it does not
                          actually run the entire function, it simply returns a generator object.
                          It only runs when you iterate over it until it is exhausted. I was
                          effectively measuring how long it took to *create* the generator, not
                          iterate over it.

                          Thanks for correcting me.

                          Frank

                          Comment

                          • Miki

                            #14
                            Re: Speed up this code?

                            Hello Martin,

                            You can use gmpy (http://gmpy.sourceforge.net/)

                            def primes():
                            n = 2
                            while 1:
                            yield long(n)
                            n = gmpy.next_prime (n)

                            HTH,
                            Miki
                            If it won't be simple, it simply won't be. [Hire me, source code]


                            Comment

                            Working...