'Where are these allocations coming from and how does declaring the parameters' types prevent them?
So I'm learning Julia by solving ProjectEuler problems and I came up with this code for 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)")
Which yields
0.106938 seconds (36.28 k allocations: 2.239 MiB, 38.39% compilation time)
size: 71, a: -61, b: 971
a*b = -59231
Now, by replacing the parameters in the function longestConsecutivePrimes for
function longestConsecutivePrimes(modA::Int64, modB::Int64)
The script, when run in a separate terminal independent from the one before, yields
0.064875 seconds (1 allocation: 16 bytes)
size: 71, a: -61, b: 971
a*b = -59231
Which is double as fast and has just 1 allocation.
Each script run was made in the linux terminal, not in the Julia REPL, closing the terminal between each run, so one run doesn't "profit" from the other's compilations.
Where were the allocations coming from and how does declaring the parameters' types prevent them?
I feel like understanding this will help me improve previous and future Julia scripts I write.
Solution 1:[1]
You were timing compilation. If you run the untyped function again, you'll see that it runs without extra allocation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Oscar Smith |
