On 23.07.2015 11:01, Xavier Leroy wrote:
> On 23/07/2015 10:35, Sébastien Hinderer wrote:
>> What's the most efficient way to compare floats, please?
>> Is it the polymorphic compare function, or is there a more specialized
>> version of it?
> You'll get good performance by type-specializing Pervasives.compare:
>
> let compare_float (x: float) (y: float) = compare x y
>
> If you're absolutely sure your floats are not NaN, you can shave a few
> CPU cycles:
>
> let compare_float (x: float) (y: float) =
> if x < y then -1 else if x > y then 1 else 0
>
The assembler code says compare_float is directly compiled to a function that
compares the 2 values
in xmm0 and xmm1 registers, while Pervasives.compare is a library function written in
C doing the same thing.
The assembler code looks very very good.
But I doubt that you could measure a difference. The type system will always
yield the float_compare function, doesn't it? So far my quickcheck...
--- Assembler code of your suggested function:
camlTest_comparefl3__compare_float_1008:
.cfi_startproc
L102:
movsd (%rbx), %xmm0
movsd (%rax), %xmm1
comisd %xmm1, %xmm0
jbe .L101
movq $-1, %rax
ret
.align 4
L101:
comisd %xmm0, %xmm1
jbe .L100
movq $3, %rax
ret
.align 4
L100:
movq $1, %rax
ret
.cfi_endproc
--- C code of library function:
CAMLprim value caml_float_compare(value vf, value vg)
{
double f = Double_val(vf);
double g = Double_val(vg);
if (f == g) return Val_int(0);
if (f < g) return Val_int(-1);
if (f > g) return Val_int(1);
/* One or both of f and g is NaN. Order according to the
convention NaN = NaN and NaN < x for all other floats x. */
if (f == f) return Val_int(1); /* f is not NaN, g is NaN */
if (g == g) return Val_int(-1); /* g is not NaN, f is NaN */
return Val_int(0); /* both f and g are NaN */