【发布时间】:2015-02-06 00:10:14
【问题描述】:
第二次编辑: github 上的This pull request 将解决此问题。只要运行 Julia v0.5+,匿名函数就和普通函数一样快。所以案件结束了。
编辑:我已将问题和函数定义更新为更一般的情况。
举个简单的例子,当一个函数被传递给一个函数或者一个函数被定义在一个函数中时,Julia 编译器似乎并没有进行优化。这让我感到惊讶,因为这在优化包中很常见。我是正确的还是我在做一些愚蠢的事情?一个简单的例子如下:
f(a::Int, b::Int) = a - b #A simple function
function g1(N::Int, fIn::Function) #Case 1: Passing in a function
z = 0
for n = 1:N
z += fIn(n, n)
end
end
function g2(N::Int) #Case 2: Function defined within a function
fAnon = f
z = 0
for n = 1:N
z += fAnon(n, n)
end
return(z)
end
function g3(N::Int) #Case 3: Function not defined within function
z = 0
for n = 1:N
z += f(n, n)
end
return(z)
end
然后我运行以下代码对这三种情况进行计时:
#Run the functions once
g1(10, f)
g2(10)
g3(10)
@time g1(100000000, f)
@time g2(100000000)
@time g3(100000000)
时间安排是:
elapsed time: 5.285407555 seconds (3199984880 bytes allocated, 33.95% gc time)
elapsed time: 5.424531599 seconds (3199983728 bytes allocated, 32.59% gc time)
elapsed time: 2.473e-6 seconds (80 bytes allocated)
前两种情况需要大量内存分配和垃圾回收。谁能解释一下原因?
【问题讨论】:
标签: julia