Plot using @timed

I have implemented three functions to calculate the Fibonacci numbers like the following:

function fib(n::Integer)::BigInt
if n <= 1
n
else
fib(n-1) + fib(n-2)
end
end

**

fib2(n::Integer)::BigInt =round(BigInt,((1+sqrt(BigFloat(5)))/2)^n / sqrt(BigFloat(5)))

**

global cache = Dict{BigInt, BigInt}(0 => 0, 1 => 1)
function fib3(n::Integer)
global cache
if haskey(cache, n)
        cache[n]
else
cache[n] = fib3(n-1) + fib3(n-2)
end
end

**
How can I use the macro @timed to plot the time and memory consumption of the
various functions to calculate Fibonacci numbers? I will be appreciated if someone can give me an example according to my code.

Updates :
I tried to do something like this

x=[1:3] 
fib=[fib(5),fib2(5),fib3(5)]
y= [@timed fib[i] for i = 1:3]
using Plots
plot(x,y)

but it dosen’t work and i think the problem is how to handel ( plot ) in my case

Didn’t you ask that already here? How to access the data in @timed and plot directly

First you have an issue, you declare a function fib then declare fib as an array…so things go weird. If I rename your function to fib1 things work better…

This might not be the most elegant way of doing this but:

function record(f, a)
    val, time, bytes, gctime, memallocs = @timed f(a)
    (time=time, bytes=bytes, gctime=gctime, memallocs=memallocs)
end

x=[1:3]
fib=[fib1, fib2, fib3]
y= [record(fib[i], 10).time for i = 1:3]
using Plots
plot(x,y)

If you want bytes you can change .time to .bytes when setting Y.

1 Like

Thank you for your reply.I want to summary what i understood from your code.

first you generate a function called " record " to store the output data of @timed like ( value , time , bytes …etc ) so i can’t access the output data directly from @timed ?
and after this in the following line you just evaluate the time of fib1(10) , fib2(10) , fib3(10)
y= [record(fib[i], 10).time for i = 1:3]

Is there a way to change the values on the x-axis from [1:3] to be string ? like Fib1 , Fib2…etc?

I’m not an expert at Julia you might be able to do (@timed fib1(5))[2] maybe? Granted you’ll have to remember what [2] is, or [3] is. @timed fib1(5)[2] probably won’t work since that will try to take the 2nd returnvalue from fib1 I believe…

Probably, you would need to check the Plots documentation, I’m not an expert at that either. :slight_smile:

Another thing to note with your original code:

fib=[fib(5),fib2(5),fib3(5)]

Actually creates an array of 3 items, with the return value of the functions…the functions are executed at that point, not later when you referenced them. So if your @timed had worked it would return the amount of time to access the array element…

fib=[fib1, fib2, fib3]
y= [(@timed fib[i](5))[2] for i = 1:3]

might work more like your original code desired.

1 Like