r/programminghelp • • May 17 '18

Two programs that do the same thing with very different execution times

I have written the same (well, I think they are the same) program in both Java and Python:

Java:

public static void main(String[] args){
    int i = 1;
    while (true){
        if (factor(i)){
            break;
        }
        i++;
    }
    System.out.println(i);
}
public static boolean factor(int n){
    for (int i = 2; i <= 20; i++){
        if (n%i!=0){
            return false;
        }
    }
    return true;
}

Python:

def main():
    i = 1
    while True:
    	    if factor(i):
		    break
	    i+=1
    print(i)

def factor(n):
    for i in range(2,21):
	if n%i!=0:
		return False
    return True

The Java program runs in less than a second, and the Python version runs in 107 seconds. What is the reason for this difference? I was under the impression that Python is generally faster than Java.

5 Upvotes

7 comments sorted by

3

u/Show_Me_Your_Stache May 18 '18

I don't think they are the same. Your Python has an indentation error and should be as below - I apologize if it already is but on mobile it looks like it isn't.

def main():
    i = 1
    while True:
        if factor(i):
            break
        i+=1
    print(i)

def factor(n):
    for i in range(2,21):
        if n%i!=0:
            return False
    return True

with that being said, I think it'll now be slower. 😁

2

u/Ovil101 May 18 '18

Just checked, the indentation is as how you showed, it was just an error with formatting on reddit.

3

u/[deleted] May 18 '18 edited May 18 '18

As /u/Show_Me_Your_Stache said, the two pieces of code aren't exactly identical. However, even when they are, Java in this situation runs much faster than Python.

Two big reasons I can think that play a part in this are:

  • Python is not strictly/statically typed unlike Java. You define the variable i and that can contain a string, an array, an integer, etc. When executing, it has to check what type of data this is, whereas in Java this is statically typed as an int. Doesn't sound like a big issue but when you're interacting with the variable literally billions of times, it adds up.

  • Java is a compiled language, whereas Python is interpreted. This allows Java to predict and optimize itself much better.

Same functionality written in similar languages to Python like PHP (https://repl.it/repls/DrearyEllipticalInsurance) and Ruby (https://repl.it/repls/ClassicWrithingProjections) performs just as poorly for the same reasons.

1

u/Ovil101 May 18 '18

The code is indented correctly, however I did learn that Python is generally slower than Java.

3

u/serg06 May 18 '18 edited May 18 '18

Python is generally the slowest. I think it's b/c Python's memory model messes with CPU prediction, so it can't do crazy optimizations.

Edit: Jeez wtf, can't even get it below 60 seconds using Numpy. Idk why Python's so slow.

C gave same speed as Java btw.

1

u/dashingderpderp May 19 '18 edited May 19 '18

Python is an interpreted language, meaning once it reaches a line of code, it will compile it and execute it. A loop with 5 lines of code inside it that executes 100 times will do 500 different compilations. So anything where a lot of lines of code are executed, like in a loop, the overhead of creating machine code for each line will stack up. The obvious way to circumvent it is to compile the code beforehand before executing it.

A few solutions already do this. The below code, which is JIT compiled by Numba executes in just 1 second on my machine:

from numba import jit

@jit
def main():
    i = 1
    while True:
        if factor(i):
            break
        i+=1
    print(i)

@jit
def factor(n):
    for i in range(2,21):
        if n%i!=0:
            return False
    return True

main()

Numba comes prepackaged with Anaconda, if you use that. JIT compilation works similar to how Java works.

2

u/DTHCND Sep 02 '18

Great explanation.