Why is it taking so long to execute loop code in Python compared to Java or C


Why is it taking so long to execute loop code in Python compared to Java or C

counter = 0
q = pow(2, 16) - 1
m = pow(2,20)
z = 7 * 16 ** 3 + 12 * 16 ** 2

for cs in range(q + 1):
    for addr in range(q + 1):
        if (cs*16 + addr) % m == z:
            counter += 1
print(counter)

Compare the speed with the same in Si

int main(){
  int counter = 0;
  int q = (int) pow(2, 16)-1;
  int m = (int) pow(2,20);
  int cs;
  for (cs = 0; cs <= q ; cs++) {
    int addr;
    for (addr = 0; addr <= q ; addr++) {
      if ((cs * 16 + addr) % m == 0x7c00){
        counter++;           
      }
    }
  }
  printf("%d\n",counter);
  return 0;
}
Author: dSH, 2019-08-26

3 answers

I will not answer why the loop is running for so long, since you have already been answered. In addition, I suspect that this concerns you less than the answer to the question " How to fix it?"...

Use Numba:

from numba import jit


@jit
def test():
    counter = 0
    q = pow(2, 16) - 1
    m = pow(2, 20)
    z = 7 * 16 ** 3 + 12 * 16 ** 2

    for cs in range(q + 1):
        for addr in range(q + 1):
            if (cs * 16 + addr) % m == z:
                counter += 1

My execution speed result is 0.30512189865112305 seconds!

Library Numba provides the jit capability (just-in-time ) compiles python code into bytecode comparable in performance to Si or Fortran code. Numba supports compiling and running python code not only on CPU, but also on GPU, while the style and appearance of the program using the Numba library remains purely Python.

 8
Author: Xyanight, 2019-08-26 06:11:13

The reasons for the slowness of Python (it is slow not only in loops but in general in general):

  1. GIL (Global Interpreter Lock, global interpreter lock), but this does not apply to this example

  2. Python is an interpreted language, not a compiled language (you have to interpret all the statements again at each iteration)

  3. Dynamic typing (time spent on type checking)

    Read more here and here.

 2
Author: V-Mor, 2020-06-12 12:52:24

Python, unlike C, and even Java, is an interpreted language, not a compiled one. Add dynamic typing here, which also doesn't add speed. So we get a decrease in the execution speed.

Of course, all this is true, all other things being equal.

A lot still depends on the implementation of the algorithm itself. You can also write a loop in assembly language so that it will run slower than another algorithm that solves a similar problem in the same Python.

 1
Author: Streletz, 2019-08-26 05:38:03