Two functions:
pi_1( ) sums N terms in for loop; N is defined in global scope.
pi_2(nterms) same as pi_1( ) except that N is passed as a parameter.
Output (copied from notebook cells):
N = 10_000_000
# First run
@time pi_1()
1.580675 seconds (80.00 M allocations: 1.416 GiB, 15.24% gc time)
3.1415925535897915
@btime pi_1()
1.236 s (79998471 allocations: 1.42 GiB)
3.1415925535897915
#First run
@time pi_2(N)
0.043618 seconds (3 allocations: 76.294 MiB, 2.37% gc time)
3.1415925535897915
@btime pi_2(N)
27.620 ms (3 allocations: 76.29 MiB)
3.1415925535897915
Both functions and versioninfo() given below:
function pi_1()
mysum = 0.0
factor=1.0
k=0
for k=collect(0:N-1)
factor = k % 2 == 0 ? 1.0 : -1.0
mysum += factor/(1+(k+k))
end
4*mysum
end
function pi_2(nterms)
mysum = 0.0
factor=1.0
k=0
for k=collect(0:nterms-1)
factor = k % 2 == 0 ? 1.0 : -1.0
mysum += factor/(1+(k+k))
end
4*mysum
end
versioninfo()
Julia Version 1.10.8
Commit 4c16ff44be8 (2025-01-22 10:06 UTC)
Build Info:
Official https://julialang.org/ release
Platform Info:
OS: Linux (x86_64-linux-gnu)
CPU: 12 Ă 12th Gen Intel(R) Core(TM) i5-1235U
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-15.0.7 (ORCJIT, alderlake)
Threads: 1 default, 0 interactive, 1 GC (on 12 virtual cores)
From what I understand, the global variable âNâ is read only once by collect() inside function pi_1(). What may cause this difference in memory behaviour ?