Re: Leap Years
- Posted by Ralf Nieuwenhuijsen <nieuwen at XS4ALL.NL> Mar 03, 1998
- 770 views
|Craig wrote: |> |> Here's a lean version of leap year testing. I don't know how it |> compares to others on speed. |> ---------------- |> global function leap_year(integer y) |> -- return 1 for leap year, 0 for not |> return ( integer(y/4)*(not integer(y/100)) + integer(y/400) ) |> end function |> ---------------- Two things, This can be done faster, as the optimization page of Lucius L. Hilley stated. (and the optimize.doc in our \doc directory of Euphoria 2beta) Remainders of values of 2^n can be done with and_bits, and it will be about 3 times faster: So, you would endup with: global function leap_year(integer y) -- return 1 for leap year, 0 for not if and_bits (3,y) then if remainder (y, 100) then if remainder (y, 400) then return 1 else return 0 end if else return 1 end if else return 0 end if end function I haven't tested it, but it should be a lot faster. Esspecially because I only call the other 2 remainder, when it is needed. A short circuit like some1 asked, is a good idea, in an alternative syntax. Whatabout this: if length(s) thenif s[1] = 1 then ... stuf.. elsif length(d) thenif d[1] = 4 then .. stuff.. end if Here you state how the short-cut must be, however it is only a help-thingie, which DOES bring more clearity to a program. Euphoria itself can never decide to short-circuit, because you may call a routine after that, or do something illegal, which simply does not add to the readablity of Euphoria. And one more thing about optimizing by ex.exe: When we have a long -if -elsif chain constantly checking the same variable, could it be speed up a bit ? It is now just as long as getting variable value, compare or whatever, continue. You might also be able to optimize a quick jump into the last slice used. So that stuff like: for index = 1 to length(s) do s[index][1][2][3] = index^2 -- Yeah I know, I should use power () end for This can be optimized a lot, first of: the loop can be optimized by Euphoria to jump through the sequence s. (set step of a secondaity index to the space of an element and have the secondairy index count along. Withing the code, the position [2][3] can have a precalculated offset, into the sequence s. All the type checking (to prevent errors from happening in this kind of dangerous trick) should be done before the loop. (as I think it should always be done). Optimize on loop-level bases, please.. Ralf