Speed โ€‹โ€‹of execution of conditional instructions in comparison with mathematical functions

I will try to be as clear as I can with my question (not just ... it's not so clear to me). Suppose you have a set of IF ... THEN commands with multiple operands, for example

IF ((a==0) && (b==1) && (c==1)) THEN x=1 ELSE IF ((a==0) && (b==0) && (c==1)) THEN x=2- 

etc.

Suppose I could replace all these IFs with one mathematical function, for example x = a * n1 + b * n2 + c * n3 (this is just to give you an idea, in reality it is more complex, but also IF and operands much more)

The function comes from a previously trained artificial neural network.

I feel that when it comes to execution, a function should take a lot less time than IF, but it's just a gut feeling that comes from my old background in the assembly, where they taught us that the conditional instruction takes more than arithmetic.

Can you confirm this? maybe even provide me with a link where I can find an explanation?

Thanks in advance guys!

+5
source share
1 answer

Your gut feeling is right.

The problem is that modern processors have a pipeline, and in the pipeline, the following x instructions are loaded sequentially ready for execution. If you have a branch, an if statement, the processor does not know which code path you are going to do next, and therefore it guesses using the branch predictor, but if it is wrong, it should throw out all the pipelines and start the correct branch again.

Industry predictors in modern processors are pretty good, but if you have something that has a 50/50 chance of going one way or another, you will have many pipelines.

This is why eliminating it if the statements are good, especially in tight loops.

It seems that you have a good explanation: http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/

+4
source

Source: https://habr.com/ru/post/1246547/


All Articles