performance - Julia:使用恒定字段进行结构以优化性能

标签 performance struct julia

foo 是一个可调用的示例结构,稍后将具有其他字段。由于其中一些字段保存具有更改值的数组,因此无法将实例设为 const G。然而, bool 值b保持不变。有没有办法告诉编译器该字段永远不会改变以启用优化?在此示例中,我希望 FGH 一样快。

using BenchmarkTools

struct foo
  b::Bool
end

function (f::foo)(x)
  if f.b
    x+1
  end
end

F = foo(true)

const G = foo(true)

H(x) = x+1


@btime F(1) # 12.078 ns (0 allocations: 0 bytes)

@btime G(1) # 0.023 ns (0 allocations: 0 bytes)

@btime H(1) # 0.024 ns (0 allocations: 0 bytes)

最佳答案

您没有正确对 F 进行基准测试。这是一种方法:

julia> @btime $F(1)
  0.026 ns (0 allocations: 0 bytes)
2

问题不在于F是一个全局非常量变量,而G是一个常量,所以当访问F时它的值为在 @btime 内不稳定。

在调用前面添加 $ 会使 F 在基准测试期间成为局部变量,然后您可以看到它同样快。

此外,在这种情况下,最好对一些较大的函数进行基准测试。这是一个简单的例子:

julia> function test(x)
       s = 0
       for i in 1:10^6
           s += x(1)
       end
       s
       end
test (generic function with 1 method)

julia> @btime test($F)
  35.830 μs (0 allocations: 0 bytes)
2000000

julia> @btime test($G)
  35.839 μs (0 allocations: 0 bytes)
2000000

您还可以使用 @code_native 检查 FG 最终得到相同的 native 代码:

julia> @code_native F(1)
    .text
; ┌ @ REPL[10]:2 within `foo'
    cmpb    $0, (%rsi)
    je  L17
; │ @ REPL[10]:3 within `foo'
; │┌ @ int.jl:53 within `+'
    addq    $1, %rdx
; │└
    movq    %rdx, (%rdi)
    movb    $2, %dl
    xorl    %eax, %eax
    retq
L17:
    movb    $1, %dl
    xorl    %eax, %eax
; │ @ REPL[10]:3 within `foo'
    retq
    nopw    %cs:(%rax,%rax)
; └

julia> @code_native G(1)
    .text
; ┌ @ REPL[10]:2 within `foo'
    cmpb    $0, (%rsi)
    je  L17
; │ @ REPL[10]:3 within `foo'
; │┌ @ int.jl:53 within `+'
    addq    $1, %rdx
; │└
    movq    %rdx, (%rdi)
    movb    $2, %dl
    xorl    %eax, %eax
    retq
L17:
    movb    $1, %dl
    xorl    %eax, %eax
; │ @ REPL[10]:3 within `foo'
    retq
    nopw    %cs:(%rax,%rax)
; └

关于performance - Julia:使用恒定字段进行结构以优化性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60833083/

相关文章:

performance - 在哪里可以获得 Glassfish 3.1 管理控制台的 Oracle Performance Tuner

ios - 查找选择了哪个结构体实例

c++ - 如何在 C++ 类的初始化列表中初始化成员结构?

arrays - 在索引处增加 StaticVector

android - Sugar ORM 在初始化时阻塞 UI 线程

Java 8 DateTimeFormatter 性能

mysql解释慢在左侧连接表的位置

java - Java中有没有类似C的struct之类的东西?

Julia:ctrl+c 不会中断

Julia 数据眼不工作