I'm new to Julia. I mainly program in python.
In python, if you want to iterate over a large set of values, it is typical to construct a so-called generator to save memory usage. Here is one example code:
def generator(N):
for i in range(N):
yield i
I wonder if there is anything alike in Julia. After reading julia manual, @task macro seems to have the same (or similar) functionality as generator in python. However, after some experiments, the memory usage seems to be larger than usual array in julia.
I use @time
in IJulia to see the memory usage.
Here is my sample code:
[Update]: Add the code for generator
method
(The generator
method)
function generator(N::Int)
for i in 1:N
produce(i)
end
end
(generator version)
function fun_gener()
sum = 0
g = @task generator(100000)
for i in g
sum += i
end
sum
end
@time fun_gener()
elapsed time: 0.420731828 seconds (6507600 bytes allocated)
(array version)
function fun_arry()
sum = 0
c = [1:100000]
for i in c
sum += i
end
sum
end
@time fun_arry()
elapsed time: 0.000629629 seconds (800144 bytes allocated)
Could anyone tell me why @task
will require more space in this case?
And if I want to save memory usage as dealing with a large set of values,
what can I do?