I designed a test program to show the speed reduction caused by conditional statements.
Here is the code:
Code:
#include <iostream>
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
using namespace std;
int TestCondition(int val)
{
if(val < 23)
val = val * 20;
val -= 322;
return val;
}
int TestNoCondition(int val)
{
val = val * 20;
val -= 322;
return val;
}
int main()
{
LARGE_INTEGER temp, tc, tnc;
int val = -100;
for (int j = 190 ; j < 200 ; ++j){
QueryPerformanceCounter(&temp);
for(int i = 0; i <100000*j ;i++)
{
val += TestCondition(i*j);
}
QueryPerformanceCounter(&tc);
tc.LowPart -= temp.LowPart;
cout << val << " ";
val = -100;
QueryPerformanceCounter(&temp);
for(int i = 0; i <100000*j ;i++)
{
val += TestNoCondition(i*j);
}
QueryPerformanceCounter(&tnc);
tnc.LowPart -= temp.LowPart;
cout << val << endl;
val = 0;
cout << "With condition: " << tc.LowPart << endl;
cout << "Without condition: " << tnc.LowPart << endl;
}
return 0;
}
It needs Windows because of its precise performance counter.
This is assembly code of two functions:
This one has a condition in it. So val = val * 20 will be executed conditionaly.
Code:
push ebp
mov ebp,esp
sub esp,40h
push ebx
push esi
push edi
if(val < 23)
cmp dword ptr [ebp+8],17h
jge 0041F4A8
val = val * 20;
mov eax,dword ptr [ebp+8]
imul eax,eax,14h
mov dword ptr [ebp+8],eax
val -= 322;
mov eax,dword ptr [ebp+8]
sub eax,142h
mov dword ptr [ebp+8],eax
return val;
mov eax,dword ptr [ebp+8]
This one has no condition:
Code:
push ebp
mov ebp,esp
sub esp,40h
push ebx
push esi
push edi
val = val * 20;
mov eax,dword ptr [ebp+8]
imul eax,eax,14h
mov dword ptr [ebp+8],eax
val -= 322;
mov eax,dword ptr [ebp+8]
sub eax,142h
mov dword ptr [ebp+8],eax
return val;
mov eax,dword ptr [ebp+8]
In my PC tnc is half of tc.