Note that there are some explanatory texts on larger screens.

plurals
  1. POOptimizing python for loops
    primarykey
    data
    text
    <p>Here are two programs that naively calculate the number of prime numbers &lt;= n.<br> One is in Python and the other is in Java.<br></p> <pre><code>public class prime{ public static void main(String args[]){ int n = Integer.parseInt(args[0]); int nps = 0; boolean isp; for(int i = 1; i &lt;= n; i++){ isp = true; for(int k = 2; k &lt; i; k++){ if( (i*1.0 / k) == (i/k) ) isp = false; } if(isp){nps++;} } System.out.println(nps); } } `#!/usr/bin/python` import sys n = int(sys.argv[1]) nps = 0 for i in range(1,n+1): isp = True for k in range(2,i): if( (i*1.0 / k) == (i/k) ): isp = False if isp == True: nps = nps + 1 print nps </code></pre> <p>Running them on n=10000 I get the following timings.<br> shell:~$ time python prime.py 10000 &amp;&amp; time java prime 10000<br> 1230<br></p> <p>real 0m49.833s<br> user 0m49.815s<br> sys 0m0.012s<br> 1230<br></p> <p>real 0m1.491s<br> user 0m1.468s<br> sys 0m0.016s<br></p> <p>Am I using for loops in python in an incorrect manner here or is python actually just this much slower?<br> </p> <p>I'm not looking for an answer that is specifically crafted for calculating primes but rather I am wondering if python code is typically utilized in a smarter fashion.</p> <p>The Java code was compiled with javac 1.6.0_20<br> Run with java version "1.6.0_18" <br> OpenJDK Runtime Environment (IcedTea6 1.8.1) (6b18-1.8.1-0ubuntu1~9.10.1) OpenJDK Client VM (build 16.0-b13, mixed mode, sharing)</p> <p>Python is:<br> Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload