Created
August 9, 2013 17:57
-
-
Save johnmyleswhite/6195659 to your computer and use it in GitHub Desktop.
Julia's type inference is where you get performance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
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.