the use of unlikely in core code.

greg-dickson
Posts: 24
Joined: Sun Nov 01, 2020 1:51 am

the use of unlikely in core code.

Postby greg-dickson » Thu May 25, 2023 1:16 am

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

ESP_Sprite
Posts: 8921
Joined: Thu Nov 26, 2015 4:08 am

Re: the use of unlikely in core code.

Postby ESP_Sprite » Thu May 25, 2023 5:48 am

I don't think we profiled it, but generally, adding unlkely() is... well... unlikely to have a detrimental effect when used correctly.

greg-dickson
Posts: 24
Joined: Sun Nov 01, 2020 1:51 am

Re: the use of unlikely in core code.

Postby greg-dickson » Fri May 26, 2023 8:59 am

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.

MicroController
Posts: 1136
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: the use of unlikely in core code.

Postby MicroController » Fri May 26, 2023 5:53 pm

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.

greg-dickson
Posts: 24
Joined: Sun Nov 01, 2020 1:51 am

Re: the use of unlikely in core code.

Postby greg-dickson » Sun May 28, 2023 1:39 am

Thanks MicroController that's useful information

Who is online

Users browsing this forum: Baidu [Spider] and 140 guests