Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is comparing double faster than uint64?

I analysed the following program using Matlab's profile. Both double and uint64 are 64-bit variables. Why is comparing two double much faster than comparing two uint64? Aren't they both compared bitwise?

big = 1000000;

a = uint64(randi(100,big,1));
b = uint64(randi(100,big,1));
c = uint64(zeros(big,1));
tic;
for i=1:big
    if a(i) == b(i)
        c(i) = c(i) + 1;
    end
end
toc;

a = randi(100,big,1);
b = randi(100,big,1);
c = zeros(big,1);
tic;
for i=1:big
    if a(i) == b(i)
        c(i) = c(i) + 1;
    end
end
toc;

This is the measurement of profile:

profile screenshot

This is what tictoc measures:

Elapsed time is 6.259040 seconds.
Elapsed time is 0.015387 seconds.

The effect disappears when uint8..uint32 or int8..int32 are used instead of 64-bit data types.

like image 315
Stein Avatar asked Apr 22 '13 23:04

Stein


1 Answers

It's probably a combination of the Matlab interpreter and the underlying CPU not supporting 64-bit int types as well as the others.

Matlab favors double over int operations. Most values are stored in double types, even if they represent integer values. The double and int == operations will take different code paths, and MathWorks will have spent a lot more attention on tuning and optimizing the code for double than for ints, especially int64. In fact, older versions of Matlab did not support arithmetic operations on int64 at all. (And IIRC, it still doesn't support mixed-integer math.) When you do int64 math, you're using less mature, less tuned code, and the same may apply to ==. Int types are not a priority in Matlab. The presence of the int64 may even interfere with the JIT optimizing that code, but that's just a guess.

But there might be an underlying hardware reason for this too. Here's a hypothesis: if you're on 32-bit x86, you're working with 32-bit general purpose (integer) registers. That means the smaller int types can fit in a register and be compared using fast instructions, but the 64-bit int values won't fit in a register, and may take more expensive instruction sequences to compare. The doubles, even though they are 64 bits wide, will fit in the wide floating-point registers of the x87 floating point unit, and can be compared in hardware using fast floating-point comparison instructions. This means the [u]int64s are the only ones that can't be compared using fast single-register, single-instruction operations.

If that's the case, if you run this same code on 64-bit x86-64 (in 64-bit Matlab), the difference may disappear because you then have 64-bit wide general purpose registers. But then again, it may not, if the Matlab interpreter's code isn't compiled to take advantage of it.

like image 109
Andrew Janke Avatar answered Oct 13 '22 15:10

Andrew Janke