Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Julia run a function faster than the non-function equivalent?

Tags:

julia

So, today I decided to try Julia and I came across something odd I couldn't quite understand the reason for nor find a decent answer to with my search queries so here I am...

First, I wanted to have something to benchmark Python against, I settled for this very simple piece of code.

def test():            
    start = time()     
    a = 1              
    while a < 10000000:
        a+=1           
    print(time() - start)

This took ~0.9s to execute in Python 3.3 on my machine. Then I ran the following in Julia.

start = time()
a = 1
while a < 10000000
    a+=1
end
print(time() - start)

It took ~0.7s to execute. So I concluded that simple arithmetic performance in Julia is ~= to Python.

However, when I made it into a function, I stumbled upon the weirdness I wasn't expecting which turned my result on its head.

function test_arithmetic()
    start = time()
    a = 1
    while a < 10000000
        a+=1
    end
    print(time() - start)
end

test_arithmetic()

This codesnippet took only ~0.1s to execute, why is this?

like image 327
erb Avatar asked Oct 14 '25 07:10

erb


1 Answers

The reason is that a global variable can have its type changed at any point, which makes it hard for the compiler to optimize. This is mentioned in the Performance Tips section of the manual.

like image 95
Mr Alpha Avatar answered Oct 17 '25 07:10

Mr Alpha