This is an automated email from the ASF dual-hosted git repository.

xiaoxiang781216 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit 3cfd91351afc8709549bf1ce41655d624e4748e4
Author: ouyangxiangzhen <[email protected]>
AuthorDate: Thu Nov 5 19:52:47 2026 +0800

    lib/math32: use plain division in div64_const() with CONFIG_DEBUG_NOOPT
    
    The magic number setup in div64_const() is only a win when it is folded
    away at compile time: unfolded per call it contains several divisions
    and is far slower than a plain division.  When CONFIG_DEBUG_NOOPT is
    enabled the build runs without optimization, so just define
    div64_const() as a plain division there.
    
    Cast the division result to uint64_t so div_const() keeps the same type
    in every build: without the cast the NOOPT build gave (n) / (base) its
    plain arithmetic type while every other build returned uint64_t, which
    made the PRIu64 format used at the tick-conversion call sites a format
    mismatch in NOOPT builds.  The cast is on the result, not the operands:
    casting the dividend to uint64_t first would widen the division itself
    and turn a single 32-bit divide into a 64-bit soft division at runtime.
    
    Assisted-By: mimo-v2.6-pro
    Signed-off-by: ouyangxiangzhen <[email protected]>
---
 include/nuttx/lib/math32.h | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)

diff --git a/include/nuttx/lib/math32.h b/include/nuttx/lib/math32.h
index 5e6a2040c99..7c099b4be56 100644
--- a/include/nuttx/lib/math32.h
+++ b/include/nuttx/lib/math32.h
@@ -320,6 +320,23 @@ static inline_function uint64_t div64_const32(uint64_t n, 
uint32_t b)
   return res;
 }
 
+#ifdef CONFIG_DEBUG_NOOPT
+
+/* Without optimization the magic number setup is not folded at compile
+ * time but runs on every call (it even contains several divisions),
+ * which is far slower than a plain division.  Cast the result, not the
+ * operands: div_const() must return uint64_t in every build, but the
+ * division itself keeps the operands' native width.
+ */
+
+#  define div64_const(n, base) ((uint64_t)((n) / (base)))
+#else
+
+/* The divisor is expected to be a compile-time constant so that the
+ * magic multiplier setup below is folded away; for runtime-invariant
+ * divisors use the invdiv API instead.
+ */
+
 static inline_function uint64_t div64_const(uint64_t n, uint64_t base)
 {
   DEBUGASSERT(base > 0);
@@ -339,6 +356,7 @@ static inline_function uint64_t div64_const(uint64_t n, 
uint64_t base)
 
   return n;
 }
+#endif
 
 #define div_const(n, base) \
   ((sizeof(typeof(n)) == sizeof(uint64_t)) ? div64_const(n, base) : ((n) / 
(base)))

Reply via email to