Some alternatives to the above age
function…
Emphasis on performance, using yearmonthday
:
function age2(dob, date)
y,m,d = yearmonthday(date) .- yearmonthday(dob)
y - (m > 0 || (m == 0 && d >= 0) ? 0 : 1)
end
Emphasis on brevity and simplicity (still faster than age
):
function age3(dob, date)
y = year(date) - year(dob)
y - (dob > date - Year(y) ? 1 : 0)
end
For reference, here's the above `age` function
function age(dob, date)
age = Dates.year(date)- Dates.year(dob) -1
if Dates.month(date)>Dates.month(dob) || (Dates.month(date)==Dates.month(dob) && Dates.day(date)>=Dates.day(dob))
age += 1
end
return age
end
Are they all the same?
range = Date(1996,1,1):Day(1):Date(2010,1,1)
for d1 = range, d2 = range
age(d1, d2) ≡ age2(d1, d2) ≡ age3(d1, d2) || println(d1," ",d2)
end
Yes (no output generated). How do they perform?
julia> @btime [age(d1, d2) for d1=$range, d2=$range];
1.675 s (2 allocations: 199.61 MiB)
julia> @btime [age2(d1, d2) for d1=$range, d2=$range];
874.106 ms (2 allocations: 199.61 MiB)
julia> @btime [age3(d1, d2) for d1=$range, d2=$range];
1.470 s (2 allocations: 199.61 MiB)