Note that there are some explanatory texts on larger screens.

plurals
  1. POGiven this same piece of code, why is the python version 100x+ slower than C?
    primarykey
    data
    text
    <p>I'm doing project euler Q14.</p> <blockquote> <p>Which starting number, under one million, produces the longest collatz chain?</p> </blockquote> <p>I was very surprised to see someone who could get a result in 0.7sec. More surprised when I see it is merely a naive brute force solution.</p> <p>I was skeptical as I spent so much time to optimize my python version, getting the runtime down to about a minute. So I ran the code myself... OP wasn't lying. </p> <p>I translated the same code to Python, it failed to terminate after 5 minutes.</p> <p>What gives?</p> <p>C version : <a href="http://codepad.org/VD9QJDkt" rel="nofollow">http://codepad.org/VD9QJDkt</a></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; int main(int argc, char **argv) { int longest = 0; int terms = 0; int i; unsigned long j; clock_t begin, end; double time_spent; begin = clock(); for (i = 1; i &lt;= 1000000; i++) { j = i; int this_terms = 1; while (j != 1) { this_terms++; if (this_terms &gt; terms) { terms = this_terms; longest = i; } if (j % 2 == 0) { j = j / 2; } else { j = 3 * j + 1; } } } printf("longest: %d (%d)\n", longest, terms); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("It took %f seconds\n", time_spent); return 0; } </code></pre> <p>Python version: <a href="http://codepad.org/ZloPyEcz" rel="nofollow">http://codepad.org/ZloPyEcz</a></p> <pre><code>import time def iterative_brute_force(n): longest = 0 terms = 0 for i in range(1, n + 1): j = i this_terms = 1 while j != 1: this_terms += 1 if this_terms &gt; terms: terms = this_terms longest = i if j % 2 == 0: j = j / 2 else: j = 3 * j + 1 return longest, terms t0 = time.time() print(iterative_brute_force(10 ** 6)) t1 = time.time() total = t1-t0 print(total) </code></pre>
    singulars
    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