我最近问了关于Python的以下问题: Interpreter optimization in Python
假设我在x中有一个字符串,那么Python解释器就足够聪明了 知道:
string.replace(x, x)
应该转换为NOP
?
答案似乎是否定(虽然Python解释器能够通过窥视孔优化器some optimizations完成)。
我不知道Julia中的等价表达是什么,但是Julia能够优化这些相对明显的类型 语句?
答案 0 :(得分:4)
问题是Julia可以为LLVM提供足够的信息,以便编译器可以优化事物吗?
从您的示例是,您可以使用code_native进行验证。例如,答案是预乘的,并且对x的不必要的赋值被优化掉,并且函数总是返回常量
julia> f()=(x=7*24*60*60)
f (generic function with 1 method)
julia> code_native(f,())
.section __TEXT,__text,regular,pure_instructions
Filename: none
Source line: 1
push RBP
mov RBP, RSP
mov EAX, 604800
Source line: 1
pop RBP
ret
它有时会更进一步,因为类型信息可以提供更多知识。相反的是,如果可能的话,应该避免 任何 类型和全局变量。
在情况I中,需要进行比较,因为y可能大于256,但在第二种情况下,因为它只有1个字节,所以它的值不能大于256,该功能将被优化为始终返回1.
julia> g(y::Int16)=(y<256?1:0)
g (generic function with 1 method)
julia> code_native(g,(Int16,))
.section __TEXT,__text,regular,pure_instructions
Filename: none
Source line: 1
push RBP
mov RBP, RSP
cmp DI, 256
Source line: 1
setl AL
movzx EAX, AL
pop RBP
ret
julia> g(y::Int8)=(y<256?1:0)
g (generic function with 2 methods)
julia> code_native(g,(Int8,))
.section __TEXT,__text,regular,pure_instructions
Filename: none
Source line: 1
push RBP
mov RBP, RSP
mov EAX, 1
Source line: 1
pop RBP
ret