Page 1 of 1

the use of unlikely in core code.

Posted: Thu May 25, 2023 1:16 am
by greg-dickson
I was looking through https://github.com/espressif/esp-idf/bl ... sp_check.h
and I noticed quite a lot of calls to unlikely()

Does anyone know if profiling has been done and this is actually a useful addition or is it simply a coding style.

I know it can be a contentious issue but I am just curious if in this case this is fact based or not.

Thanks.
Gregory

Re: the use of unlikely in core code.

Posted: Thu May 25, 2023 5:48 am
by ESP_Sprite
I don't think we profiled it, but generally, adding unlkely() is... well... unlikely to have a detrimental effect when used correctly.

Re: the use of unlikely in core code.

Posted: Fri May 26, 2023 8:59 am
by greg-dickson
Thanks ESP_Sprite
Haha
It seems that with modern compilers it generally unlikely :) to do much at all.
Some people even think it can have a detrimental effect.
But really that is one can of worms I am not really keen to open.

Thanks for the answer it helps clarify a small point.

Re: the use of unlikely in core code.

Posted: Fri May 26, 2023 5:53 pm
by MicroController
I found that the builtin_expect (C) and [[likely]] (C++) consistently do what I expect, i.e. make sure it is the unlikely case which code gets moved so that the likely case does not have to execute a branch. Since the branching itself is pretty cheap on ESPs ("penalty" of 1 (or 2? can't remember) CPU cycles on RISC-V's) using the hints makes most sense in tight loops. However, if you're lucky you may experience a significant speedup on "rarely" executed code sections too, namely if the "unlikely" code gets moved out of the way so that it normally does not need to be loaded from flash and does not "spoil" the cache.
GCC is (sometimes) even able to propagate the "likeliness" to other code, e.g. via the "likeliness" of a function's return value which may add up to more "unlikely" code being moved out of the way.

Re: the use of unlikely in core code.

Posted: Sun May 28, 2023 1:39 am
by greg-dickson
Thanks MicroController that's useful information