Julia 与 Python 编译器/解释器优化

Ame*_*ina 5 optimization julia

我最近问了以下关于Python的问题: Python中的解释器优化

假设我在 x 中有一个字符串,Python 解释器是否足够聪明来知道:string.replace(x, x)应该转换为 a NOP

答案似乎是否定的(尽管Python解释器能够通过窥视孔优化器进行一些优化)。

我不知道 Julia 中的等效表达式是什么,但是 Julia 是否能够优化这些类型的相对明显的语句?

waT*_*eim 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
Run Code Online (Sandbox Code Playgroud)

打字优化

有时它可以走得更远,因为可以从类型信息中获得更多知识。相反,如果可能的话,应避免Any类型和全局变量。

例子

在情况一中,需要进行比较,因为 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
Run Code Online (Sandbox Code Playgroud)

案例二

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
Run Code Online (Sandbox Code Playgroud)