Note that there are some explanatory texts on larger screens.

plurals
  1. POVery large execution time differences for virtually same C++ and Python code
    primarykey
    data
    text
    <p>I was trying to write a solution for <a href="http://projecteuler.net/problem=12" rel="nofollow">Problem 12 (Project Euler)</a> in Python. The solution was just too slow, so I tried checking up other people's solution on the internet. I found <a href="http://www.staticallylinked.com/2010/03/finding-first-triangle-number-to-have.html" rel="nofollow">this code</a> written in C++ which does virtually the same exact thing as my python code, with just a few insignificant differences.</p> <p>Python:</p> <pre><code>def find_number_of_divisiors(n): if n == 1: return 1 div = 2 # 1 and the number itself for i in range(2, n/2 + 1): if (n % i) == 0: div += 1 return div def tri_nums(): n = 1 t = 1 while 1: yield t n += 1 t += n t = tri_nums() m = 0 for n in t: d = find_number_of_divisiors(n) if m &lt; d: print n, ' has ', d, ' divisors.' m = d if m == 320: exit(0) </code></pre> <p>C++:</p> <pre><code>#include &lt;iostream&gt; int main(int argc, char *argv[]) { unsigned int iteration = 1; unsigned int triangle_number = 0; unsigned int divisor_count = 0; unsigned int current_max_divisor_count = 0; while (true) { triangle_number += iteration; divisor_count = 0; for (int x = 2; x &lt;= triangle_number / 2; x ++) { if (triangle_number % x == 0) { divisor_count++; } } if (divisor_count &gt; current_max_divisor_count) { current_max_divisor_count = divisor_count; std::cout &lt;&lt; triangle_number &lt;&lt; " has " &lt;&lt; divisor_count &lt;&lt; " divisors." &lt;&lt; std::endl; } if (divisor_count == 318) { exit(0); } iteration++; } return 0; } </code></pre> <p>The python code takes 1 minute and 25.83 seconds on my machine to execute. While the C++ code takes around 4.628 seconds. Its like 18x faster. I had expected the C++ code to be faster but not by this great margin and that too just for a simple solution which consists of just 2 loops and a bunch of increments and mods.</p> <p>Although I would appreciate answers on how to solve this problem, the main question I want to ask is <strong>Why is C++ code so much faster? Am I using/doing something wrongly in python?</strong></p> <hr> <p><strong>Replacing range with xrange:</strong></p> <p>After replacing range with xrange the python code takes around 1 minute 11.48 seconds to execute. (Around 1.2x faster)</p>
    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