Skip to content

Instantly share code, notes, and snippets.

@johnmyleswhite
Created August 9, 2013 17:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnmyleswhite/6195659 to your computer and use it in GitHub Desktop.
Save johnmyleswhite/6195659 to your computer and use it in GitHub Desktop.
Julia's type inference is where you get performance
# Always ignore one run
x = 0
@elapsed for i in 1:100_000_000
x += 1
end # => 3.330939854
# Second time is more accurate
x = 0
@elapsed for i in 1:100_000_000
x += 1
end # => 3.287221881
function foo()
x = 0
t = @elapsed for i in 1:100_000_000
x += 1
end
println(t)
end
foo() # => 0.028839841
foo() # => 0.028527174
@johnmyleswhite
Copy link
Author

Running identical code in a function is 100x faster. Why? Because the compiler can determine that the type of x is invariant, which isn't guaranteed in the global namespace.

@johnmyleswhite
Copy link
Author

Note, for example, that this code gets compiled to code that's nearly maximally efficient:

julia> function bar()
       x = 0
       for i in 1:100_000_000
       x += 1
       end
       return x
       end
# methods for generic function bar
bar() at none:2

julia> code_native(bar, ())
    .section    __TEXT,__text,regular,pure_instructions
Filename: none
Source line: 3
    push    RBP
    mov RBP, RSP
    mov EAX, 100000000
Source line: 3
    dec RAX
    jne -9
    mov EAX, 100000000
Source line: 6
    pop RBP
    ret

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment