【发布时间】:2022-02-02 02:32:25
【问题描述】:
所以我通过解决 ProjectEuler 问题来学习 Julia,我为problem 27 想出了这段代码:
function isPrime(num)
num < 2 && return false
for i in 2:trunc(Int, √num)
if num % i == 0
return false
end
end
return true
end
function quadratic(n, a, b)
return n^2 + a*n + b
end
function consecutivePrimes(a, b)
count = 0
tryNum = 0
while true
currResult = quadratic(tryNum, a, b)
!isPrime(currResult) && (return count)
count += 1
tryNum += 1
end
end
function longestConsecutivePrimes(modA, modB)
longest = (0,0,0)
for a in -modA:modA, b in -modB:modB
consecutive = consecutivePrimes(a, b)
longest[1] < consecutive && (longest = (consecutive, a, b))
end
return longest
end
A, B = 999, 1000
@time size, a, b = longestConsecutivePrimes(A, B)
println("size: $size, a: $a, b: $b")
println("a*b = $(a*b)")
产量
0.106938 seconds (36.28 k allocations: 2.239 MiB, 38.39% compilation time)
size: 71, a: -61, b: 971
a*b = -59231
现在,通过将函数longestConsecutivePrimes中的参数替换为
function longestConsecutivePrimes(modA::Int64, modB::Int64)
脚本在独立于前一个终端的单独终端中运行时,会产生
0.064875 seconds (1 allocation: 16 bytes)
size: 71, a: -61, b: 971
a*b = -59231
它的速度是原来的两倍,并且只有 1 次分配。
每个脚本运行都是在 linux 终端中进行的,而不是在 Julia REPL 中,每次运行之间都会关闭终端,因此一次运行不会从另一次的编译中“获利”。
分配是从哪里来的?声明参数的类型如何防止分配?
我觉得理解这一点将有助于我改进我以前和未来编写的 Julia 脚本。
【问题讨论】:
-
您是否遵循proper benchmarking 的良好做法?
标签: optimization julia allocation