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?

有帮助吗?

解决方案

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.

其他提示

I found the answer, it has to do with how it is faster to store local variables compared to globals.

The equivalent question for Python (which led me to test if the same applied to Julia) can be found here.

It turns out that this code-snippet runs in ~0.7s as well.

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

test_arithmetic()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top