473,806 Members | 2,845 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

May 26 '06
13 1504
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

May 26 '06 #11
On 27/05/2006 6:57 AM, be************@ lycos.com wrote:
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:


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?

May 26 '06 #12

Gregory Petrosyan wrote:
# 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


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

May 27 '06 #13
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
http://pythonwise.blogspot.com/

May 28 '06 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
23079
by: Yang Li Ke | last post by:
Hi guys, Is it possible to know the internet speed of the visitors with php? Thanx -- Yang
4
1750
by: WindAndWaves | last post by:
Hi Gurus I am building my first ever PHP site. Should I worry about speed? These are the parameters of my site - MySQL database with about 500 records (about 50 fields each) and a couple of small related tables - about two or three visitors at the same time - hosted on fast and large server in the US
34
2485
by: Jacek Generowicz | last post by:
I have a program in which I make very good use of a memoizer: def memoize(callable): cache = {} def proxy(*args): try: return cache except KeyError: return cache.setdefault(args, callable(*args)) return proxy which, is functionally equivalent to
28
2612
by: Maboroshi | last post by:
Hi I am fairly new to programming but not as such that I am a total beginner From what I understand C and C++ are faster languages than Python. Is this because of Pythons ability to operate on almost any operating system? Or is there many other reasons why? I understand there is ansi/iso C and C++ and that ANSI/ISO Code will work on any system If this is the reason why, than why don't developers create specific Python Distrubutions...
7
3051
by: YAZ | last post by:
Hello, I have a dll which do some number crunching. Performances (execution speed) are very important in my application. I use VC6 to compile the DLL. A friend of mine told me that in Visual studio 2003 .net optimization were enhanced and that i must gain in performance if I switch to VS 2003 or intel compiler. So I send him the project and he returned a compiled DLL with VS 2003. Result : the VS 2003 compiled Dll is slower than the VC6...
11
2008
by: Jim Lewis | last post by:
Has anyone found a good link on exactly how to speed up code using pyrex? I found various info but the focus is usually not on code speedup.
6
6257
by: Jassim Rahma | last post by:
I want to detect the internet speed using C# to show the user on what speed he's connecting to internet?
8
6506
by: SaltyBoat | last post by:
Needing to import and parse data from a large PDF file into an Access 2002 table: I start by converted the PDF file to a html file. Then I read this html text file, line by line, into a table using a code loop and an INSERT INTO query. About 800,000 records of raw text. Later, I can then loop through and parse these 800,000 strings into usable data using more code. The problem I have is that the conversion of the text file, using a...
11
2253
by: blackx | last post by:
I'm using clock() to measure the speed of my code (testing the speed of passing by value vs passing by reference in function calls). The problem is, the speed returned by my code is always 0.0000000 Can you check if I'm using the clock() function correctly? the function is finding the number in the array that is closest to a number given by the user. Here is the code for the pass by value function. Thanks for the help! relevant code:
47
1442
by: Mike Williams | last post by:
I'm trying to decide whether or not I need to move to a different development tool and I'm told that VB6 code, when well written, can be ten times faster than vb.net, but that if its badly written it can be ten times slower. Is that correct? I'm quite competent at writing code myself and so most of my code will be quite well written, and I don't want to move to vb.net if well written VB6 code is ten times faster. Have I been told the...
0
9719
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10110
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9187
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6877
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5546
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3850
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.