FWIW, adinn's branchless code together with
PR https://git.openjdk.java.net/jdk/pull/4660
make both methods less vulnerable to timing attacks.


Greetings
Raffaello


On 2021-07-02 15:50, Andrew Haley wrote:
On Fri, 2 Jul 2021 11:06:06 GMT, Andrew Dinn <ad...@openjdk.org> wrote:

You can also do that branchlessly which might prove better

```
      long result = Math.multiplyHigh(x, y);
      result += (y & (x >> 63));
      result += (x & (y >> 63));
      return result;
```
I doubt very much that it would be better, because these days branch prediction 
is excellent, and we also have conditional select instructions. Exposing the 
condition helps C2 to eliminate it if the range of args is known. The `if` code 
is easier to understand.

Benchmark results, with one of the operands changing signs every iteration, 
1000 iterations:


Benchmark                  Mode  Cnt     Score    Error  Units
MulHiTest.mulHiTest1   (aph)     avgt    3  1570.587 ± 16.602  ns/op
MulHiTest.mulHiTest2   (adinn)   avgt    3  2237.637 ±  4.740  ns/op

In any case, note that with this optimization the unsigned mulHi is in the 
nanosecond range, so Good Enough. IMO.

-------------

PR: https://git.openjdk.java.net/jdk/pull/4644

Reply via email to