comphead commented on code in PR #12342:
URL: https://github.com/apache/arrow-rs/pull/12342#discussion_r4635746985


##########
arrow-cast/src/cast/decimal.rs:
##########
@@ -226,11 +257,12 @@ where
         // div is >= 10 and so this cannot overflow
         let (d, r) = x.div_rem_wrapping(div);
 
-        // Round result
-        let adjusted = match x >= I::Native::ZERO {
-            true if r >= half => d.add_wrapping(I::Native::ONE),
-            false if r <= half_neg => d.sub_wrapping(I::Native::ONE),
-            _ => d,
+        // Round half away from zero. Whether a value rounds depends on the
+        // data, so select the result instead of branching on it.
+        let adjusted = if x >= I::Native::ZERO {
+            std::hint::select_unpredictable(r >= half, 
d.add_wrapping(I::Native::ONE), d)
+        } else {
+            std::hint::select_unpredictable(r <= half_neg, 
d.sub_wrapping(I::Native::ONE), d)
         };

Review Comment:
   A correction to my last comment: the bot shows the case you expected, on 
Linux. This PR against c48302010:
   
   | Benchmark | arm64 (Neoverse-V2) | amd64 | x86-64-v3 |
   |---|---:|---:|---:|
   | `cast decimal256 to decimal128 512` | -27% | -29% | -31% |
   | ... `mixed sign` | -12% | -17% | -17% |
   | ... `zero remainder` | +11% | +10% | +3% |
   | `cast decimal128 to decimal128 512 with lower scale (infallible)` | 0% | 
0% | 0% |
   | ... `mixed sign` | 0% | 0% | -5% |
   | ... `zero remainder` | 0% | 0% | -2% |
   
   So when no remainder rounds, the select is 3% to 11% slower than the branch. 
The M5 hid this because `main` already compiles that step to `csel` on macOS. 
For `aarch64-unknown-linux-gnu`, `main` branches on the result of `r >= half` 
(a `tbz` right after the compare), and this PR selects. With the branch, the 
zero-remainder case takes 96 µs against 149 µs for random remainders on arm64, 
and 72 µs against 112 µs on amd64. With the select, both take 107 µs to 109 µs 
on arm64 and 79 µs on amd64.
   
   Going back to the branch would likely give up most of the 27% to 31% on 
random remainders. On the M5, where `main` already selects, this PR gains only 
6% on that case. On macOS it would also bring back the +88% that inlining the 
check caused. I'd keep the select, since the loss on remainders that never 
round is smaller than the gain on remainders that do, but I'm happy to switch 
back to the branch if you prefer it for Linux.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to