Обсуждение: Optimize multiplications/divisions by 2 using bit shifts in hot paths

Поиск
Список
Период
Сортировка

Optimize multiplications/divisions by 2 using bit shifts in hot paths

От
Chao Li
Дата:
Hi Hackers,

This patch uses left/right shift operators to optimize *2 and /2 operations in some functions that are in critical paths.

For unsigned int, *2 and /2 exactly equal to <<1 and >>1.

For signed int:
 * /2 exactly equals to >>1 when a value is non-negative, this patch ensures only changes non-negative variables
 * *2 might be different from <<1 if a value is close to MAX_INT, however, in that case x*2 will result in a undefined result, thus existing code should have ensured *2 should not exceed MAX_INT.

"make check" passes with this patch.

Best regards,
Chao Li (Evan)
---------------------
HighGo Software Co., Ltd.
https://www.highgo.com/
Вложения

Re: Optimize multiplications/divisions by 2 using bit shifts in hot paths

От
David Rowley
Дата:
On Fri, 19 Sept 2025 at 14:11, Chao Li <li.evan.chao@gmail.com> wrote:
> This patch uses left/right shift operators to optimize *2 and /2 operations in some functions that are in critical
paths.
>
> For unsigned int, *2 and /2 exactly equal to <<1 and >>1.

The compiler is most likely going to do this anyway. Try it out at
https://godbolt.org/z/Y538Yd4Ka

What maybe is worth looking at is verifying which of these variables
is signed when it really should be unsigned. Dividing by 2 and >> 1
aren't the same for negative numbers.

David



Re: Optimize multiplications/divisions by 2 using bit shifts in hot paths

От
Chao Li
Дата:


On Sep 19, 2025, at 10:22, David Rowley <dgrowleyml@gmail.com> wrote:

On Fri, 19 Sept 2025 at 14:11, Chao Li <li.evan.chao@gmail.com> wrote:
This patch uses left/right shift operators to optimize *2 and /2 operations in some functions that are in critical paths.

For unsigned int, *2 and /2 exactly equal to <<1 and >>1.

The compiler is most likely going to do this anyway. Try it out at
https://godbolt.org/z/Y538Yd4Ka

Thanks for the info.


What maybe is worth looking at is verifying which of these variables
is signed when it really should be unsigned. Dividing by 2 and >> 1
aren't the same for negative numbers.


Yes, I think I mentioned in the commit comment. For negative numbers, /2 doesn’t equal to >>1. I saw a lot of variables of type “int" named as “xxx_len”, feels like they can be unsigned. But we need to carefully check every one individually if we want change their types.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/