C++ issues choosing a function at run time
I'm at a basic level with C++ so please excuse me if I am missing something obvious.
I'm planning a program that can run in two modes. The mode it runs in will be decided by a flag in a config file that the program reads when it first starts. After reading this config file the program will drop into a loop that will loop millions of times.
At one point within the loop the code does different things depending on what mode it was set in from the config file.
Clearly I could use an IF. If mode 1 do actions1 else if mode 2 do actions2. But I would like to save on the time that IF will take (bearing in mind it will happen millions of times).
To do this I considered putting actions1 and actions2 in their own functions and use a function pointer.
Then I can set the function pointer as the config file is being read before the loop and just use that pointer in place of the IF.
But, the problem is when put into functions actions1 and actions2 have different arguments and so I need two function pointers to accomidate this meaning I'm back to needing an IF again.
I could ressolve this issue using global variables but I'd rather not. Can anyone suggest a way to solve this?
Or should I not be worrying about the cost of the millions of IFs, will the compiler see the descion is made and not keep making it over and over?
EDIT: Thanks for your answers. I've done a test using this very simple code:
int i = 2
int p = 10;
for(int f=0;开发者_运维问答f < 900000000; f++)
{
if(p == 10)
i = p+f;}
It actually runs 20% faster when the if is there than when I comment it out. I suppose that must be the branch hpredictor in action but I still don't know why it is faster than when no if is used at all.
On most modern processors, such as x86, there is a "branch predictor". The processor itself observes patterns in whether a conditional branch was taken or not; if you are always making the same decision, then it should be very efficient.
The best thing to do is simply to measure. Write your loop code, firstly without any conditionals (i.e. just hard-code it to do Action #1), and measure how long it takes to run e.g. 10 million iterations. Then put the if
statement back in, and measure again. There's no point worrying until you've confirmed that it makes a difference!
Firstly, this is premature optimization- the CPU's branch predictor is extremely good at this kind of thing, I'd worry about maintenance more and use inheritance rather than function pointers. Secondly, the only real way to make this faster is to pre-compile each choice and load them as separate libraries at runtime.
I'm at a basic level with C++ so please excuse me if I am missing something obvious.
The obvious solution seems to be to move the if
outside of the loop. Instead of writing:
while (...)
{
if (flag)
{
// ...
}
else
{
// ...
}
}
you can write:
if (flag)
{
while (...)
{
// ...
}
}
else
{
while (...)
{
// ...
}
}
精彩评论