top | item 31730036

(no title)

huachimingo | 3 years ago

Which one is faster? (C code) Return: see if abs(num) > x.

/logical comparison/ int greater_abs(int num, int x){ return (num > x) || (num+x < 0); }

/squared approach/ int greater_abs2(int num, int x){ return num*num > x; }

See it by yourself, with (and without) optimizations: https://godbolt.org/

What would happen if x is a compile-time constant?

discuss

order

dahart|3 years ago

Math & logic are rarely the bottleneck over memory & allocation bottlenecks, right? Does Godbolt assume x86? Does the answer change depending on whether you’re using an AMD or NVIDIA GPU, or an Apple, ARM or Intel processor? Does it depend on which instruction pipelines are full or stalled from the surrounding code, e.g., logic vs math? Hard to say if one of these will always be better. There are also other alternatives, e.g. bitmasking, that might generate fewer instructions… maybe “abs(num) > x” will beat both of those examples?

masklinn|3 years ago

> Does Godbolt assume x86?

Godbolt uses whatever compilers, targets, and optimisations you ask it to.

It is, in fact, a very useful tool for comparing different compilers, architectures, and optimization settings.

throwaway744678|3 years ago

I don't know which one is faster, but I know that one is not correct (squared approach).

saghm|3 years ago

Wouldn't the second one also potentially be incorrect due to overflow?

zasdffaa|3 years ago

Depends. In the first it will depend on the branch predictor which will depend on the relative expected magnitudes of num and x

In the 2nd, which I assume should be

    { return num*num > x * x; }
then it depends on the micro-arch, as it's one basic block so no branches and assuming a deep pipeline on x64, one multiplier (pipelined), probably this is faster for 'random-ish' num and x.

dhosek|3 years ago

Your squared approach is wrong: greater_abs2(3, 4) returns true but should return false.

omegalulw|3 years ago

They probably meant num * num > x * x

WalterGR|3 years ago

No idea.

How frequently am I calling `abs`?

jjice|3 years ago

If you write math heavy code, probably a lot more than if you're writing web apps. Depends on what kind of software you write.

astrange|3 years ago

Most questions like these have no answer because if any of the parameters is known (which it usually is) it’ll get folded away to nothing.