[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Remi Vanicat <remi.vanicat@l...> |
| Subject: | Re: [Caml-list] ASM code generated by OCAML |
Francesco Abbate <segfault@email.it> writes:
> Dear Ocamlers,
>
> ok, I confess that I'm a little bit paranoid and I often
> look to the assembler code generated by Ocaml to get an
> idea of real efficience of the compiler.
>
> While, generally speaking, the ASM code generated by ocaml
> is pretty good, I wonder why the following function
> is not decently assembled by ocaml :
> -----------------------------------------
> let rec conv n =
> let r = n mod 10
> and n' = n / 10 in
> if n' = 0 then r
> else r + 8 * (conv n')
> -----------------------------------------
> nor the C version is decently assembled by GCC
> -----------------------------------------
> int
> conv (int n)
> {
> int m = n / 10, r = n % 10;
> if (m > 0)
> return r + 8 * conv (m);
> return m;
> }
> -----------------------------------------
> So my answer is why nor Ocaml nor GCC does generate efficient
> assembler code ?
>
> I will attempt to give a tentative answer
> - for some reason the compiler does not understands the (n mod 10)
> and (n /10) both can be avaluated with a simgle "idiv"
> instruction
This require some analysis that isn't needed in general
> - for some reason the compilers does not conceive to have a loop
> which push something on the stack at each cycle.
Ocaml (and I believe GCC) only optimize code witch is tail recursive,
that is the result of the function is the result of the recursive
case.
You should transform your code into a tail rec function by hand :
let conv n =
let rec helper n mult accu =
if n = 0 then accu
else
let r = n mod 10
and n' = n / 10 in
helper n' (mult * 8) (accu + r * mult) in
helper n 1 0
As you can see, the result of the recursive function helper is the
result of the recursive call.
--
Rémi Vanicat
-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners