Re: [PATCH v2] src/port/snprintf.c: Optimize the common base=10 case in fmtint - Mailing list pgsql-hackers

From Japin Li
Subject Re: [PATCH v2] src/port/snprintf.c: Optimize the common base=10 case in fmtint
Date
Msg-id MEYP282MB16696C8F61A5610A0B660344B6859@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM
Whole thread Raw
In response to [PATCH v2] src/port/snprintf.c: Optimize the common base=10 case in fmtint  (Arjan van de Ven <arjan@linux.intel.com>)
Responses Re: [PATCH v2] src/port/snprintf.c: Optimize the common base=10 case in fmtint  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-hackers
On Wed, 27 Oct 2021 at 04:58, Arjan van de Ven <arjan@linux.intel.com> wrote:
> [PATCH v2] src/port/snprintf.c: Optimize the common base=10 case in fmtint
>
> fmtint() turns an integer into a string for a given base, and to do this
> it does a divide/modulo operation iteratively.
> The only possible base values are 8, 10 and 16
>
> On just about any CPU, divides are a pretty expensive operation, generally
> 10x to 20x or more expensive than adds or multiplies.
>
> By special casing the base values, the compiler (gcc or other) can (and will)
> replace the divide by a multiply with 0xcccccccccccccccd (for base 10) or bitops
> for base 8 and 16, yielding a lot faster code.
>
> I considered a switch statement, but since base 10 is the most common by far,
> I implemented it as a series of if/else statements with a likely() marking the 10 case.
>
> Even though this only shows up in the database creation phase of pgbench and not so much
> during the normal run time, the optimization is simple and high value enough that
> in my opinion it's worth doing
>
>


+        if (likely(base == 10)) {
+            do
+            {
+                convert[sizeof(convert) - (++vallen)] = cvt[uvalue % 10];
+                uvalue = uvalue / 10;
+            } while (uvalue);
+        } else if (base == 16) {

Why do we need likely() for base=10, however, base=16 and base=8 don't need?

-- 
Regrads,
Japin Li.
ChengDu WenWu Information Technology Co.,Ltd.



pgsql-hackers by date:

Previous
From: Kyotaro Horiguchi
Date:
Subject: Re: Setting log_connection in connection string doesn't work
Next
From: Tom Lane
Date:
Subject: Re: [PATCH v2] src/port/snprintf.c: Optimize the common base=10 case in fmtint