| | |
C++ Performance Tips
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
•
•
3. Optimizing the breaking conditions in for loops. If you know that the loop variable's range is from 0 to some +ve number AND it doesn't matter which way you traverse while looping, you can optimize the loop like this:
c++ Syntax (Toggle Plain Text)
//original loop for( int i = 0; i <= 30; i++ ) {/*do your stuff*/} //optimized loop for( int i = 30; i--; ) {/*do your stuff*/}
c Syntax (Toggle Plain Text)
i = 30; while (i--) { /*do your stuff*/ }
The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
5. Another way of optimizing loops is to unroll it:
c++ Syntax (Toggle Plain Text)
//unoptimized loop int loop_count = 50000; /* could be anything */ for( int j = 0; j < loop_count; j++ ) printf("process(%d)\n", j); //optimized one static int BLOCKSIZE = 8 ; /* The loop_count may not be divisible by BLOCKSIZE, * go as near as we can first, then tidy up. */ int i = 0; int blocklimit = (loop_count / BLOCKSIZE) * BLOCKSIZE ; /* unroll the loop in blocks of 8 */ while( i < blocklimit ) { printf("process(%d)\n", i); printf("process(%d)\n", i+1); printf("process(%d)\n", i+2); printf("process(%d)\n", i+3); printf("process(%d)\n", i+4); printf("process(%d)\n", i+5); printf("process(%d)\n", i+6); printf("process(%d)\n", i+7); /* update the counter */ i += 8; } //we already know how to optimize small loops. switch( loop_count - i ) { case 7 : printf("process(%d)\n", i); i++; case 6 : printf("process(%d)\n", i); i++; case 5 : printf("process(%d)\n", i); i++; case 4 : printf("process(%d)\n", i); i++; case 3 : printf("process(%d)\n", i); i++; case 2 : printf("process(%d)\n", i); i++; case 1 : printf("process(%d)\n", i); }
> //A quicker method is to simply use the value as an
Except your other two methods never risk an out of bounds memory access.
> 1. unsigned int arithmatic is faster than signed int.
Where's your evidence?
> 2. registers are registers ! They're simply faster than memory access.
True, but any decent compiler nowadays is far more capable of deciding which variables would be best placed in registers.
> AND it doesn't matter which way you traverse while looping,
Well if you're using it for indexing an array, and your cache is optimised in favour of incremental access, then you lose badly.
I've only ever seen counting backwards to zero save ONE instruction on those machines which specifically have a 'test-and-branch' instruction.
> Another way of optimizing loops is to unroll it:
Or just use the gcc flag -funroll-loops
Better yet, bone up on all the magic which a modern compiler can do, which doesn't involve you mauling the code into an unreadable mess.
http://gcc.gnu.org/onlinedocs/gcc-4....timize-Options
Except your other two methods never risk an out of bounds memory access.
> 1. unsigned int arithmatic is faster than signed int.
Where's your evidence?
> 2. registers are registers ! They're simply faster than memory access.
True, but any decent compiler nowadays is far more capable of deciding which variables would be best placed in registers.
> AND it doesn't matter which way you traverse while looping,
Well if you're using it for indexing an array, and your cache is optimised in favour of incremental access, then you lose badly.
I've only ever seen counting backwards to zero save ONE instruction on those machines which specifically have a 'test-and-branch' instruction.
> Another way of optimizing loops is to unroll it:
Or just use the gcc flag -funroll-loops
Better yet, bone up on all the magic which a modern compiler can do, which doesn't involve you mauling the code into an unreadable mess.
http://gcc.gnu.org/onlinedocs/gcc-4....timize-Options
@WaltP
Except if your description is true, you'd be better off using
>> Sorry but I fail to see the different between for and while loop.. Do you mean it's faster to use while instead of for?
@Salem
> //A quicker method is to simply use the value as an
Except your other two methods never risk an out of bounds memory access.
KashAI>> TRUE. So I hope that anyone able enough to understand this won't blindly copy my code.
> 1. unsigned int arithmatic is faster than signed int.
Where's your evidence?
KashAI>> I was afraid someone will ask.
. Anyway, simple answer is I don't know.
But here is what I know:
1. In VS 6.0 (on Intel H/W) a simple for loop with loop variable being unsigned is about 2 seconds faster than when loop variable is signed int. (looped some 100K and 500K times to print the value of loop variable)
2. In most cases one can see that there are seperate assemply instructions for signed and unsigned arithmetic. Which at least indicates a difference in performance.
3. Number of flags applicable (CF=carry-over-flag, SG=sign-flag, OF=overflow-flag) to signed and unsigned instructions' execution are different.
4. I'm vaguely remember an instruction called SBB (substract using borrow) which, if i'm not wrong, is only applicable to signed arithmetic.
And use of it is in case where the requested substraction of 2 signed numbers can not be completed with a single instruction due to register size.
> 2. registers are registers ! They're simply faster than memory access.
True, but any decent compiler nowadays is far more capable of deciding which variables would be best placed in registers.
KashAI>> So if I understand it right what I've written is correct, but not neccesarry.
> AND it doesn't matter which way you traverse while looping,
Well if you're using it for indexing an array, and your cache is optimised in favour of incremental access, then you lose badly.
I've only ever seen counting backwards to zero save ONE instruction on
those machines which specifically have a 'test-and-branch' instruction.
KashAI>> So in short, should one NOT optimize it this way? May be you could add some practical numbers for the benefit of readers which will help them in deciding whether to use this optimization or not?
E.g. "in 80% of cases cache is optimised in favour of incremental access" OR
"Now-a-days most machines support "'test-and-branch' instruction".
> Another way of optimizing loops is to unroll it:
Or just use the gcc flag -funroll-loops
Better yet, bone up on all the magic which a modern compiler can do,
which doesn't involve you mauling the code into an unreadable mess.
http://gcc.gnu.org/onlinedocs/gcc-4....timize-Options
KashAI>> Now that is useful info. Just checked and found that VS 6.0 and Sun Workshop 6.0 also support lopp unrolling.
Except if your description is true, you'd be better off using
c++ Syntax (Toggle Plain Text)
i = 30; while (i--) {/*do your stuff*/}
>> Sorry but I fail to see the different between for and while loop.. Do you mean it's faster to use while instead of for?
@Salem
> //A quicker method is to simply use the value as an
Except your other two methods never risk an out of bounds memory access.
KashAI>> TRUE. So I hope that anyone able enough to understand this won't blindly copy my code.
> 1. unsigned int arithmatic is faster than signed int.
Where's your evidence?
KashAI>> I was afraid someone will ask.
. Anyway, simple answer is I don't know.But here is what I know:
1. In VS 6.0 (on Intel H/W) a simple for loop with loop variable being unsigned is about 2 seconds faster than when loop variable is signed int. (looped some 100K and 500K times to print the value of loop variable)
2. In most cases one can see that there are seperate assemply instructions for signed and unsigned arithmetic. Which at least indicates a difference in performance.
3. Number of flags applicable (CF=carry-over-flag, SG=sign-flag, OF=overflow-flag) to signed and unsigned instructions' execution are different.
4. I'm vaguely remember an instruction called SBB (substract using borrow) which, if i'm not wrong, is only applicable to signed arithmetic.
And use of it is in case where the requested substraction of 2 signed numbers can not be completed with a single instruction due to register size.
> 2. registers are registers ! They're simply faster than memory access.
True, but any decent compiler nowadays is far more capable of deciding which variables would be best placed in registers.
KashAI>> So if I understand it right what I've written is correct, but not neccesarry.
> AND it doesn't matter which way you traverse while looping,
Well if you're using it for indexing an array, and your cache is optimised in favour of incremental access, then you lose badly.
I've only ever seen counting backwards to zero save ONE instruction on
those machines which specifically have a 'test-and-branch' instruction.
KashAI>> So in short, should one NOT optimize it this way? May be you could add some practical numbers for the benefit of readers which will help them in deciding whether to use this optimization or not?
E.g. "in 80% of cases cache is optimised in favour of incremental access" OR
"Now-a-days most machines support "'test-and-branch' instruction".
> Another way of optimizing loops is to unroll it:
Or just use the gcc flag -funroll-loops
Better yet, bone up on all the magic which a modern compiler can do,
which doesn't involve you mauling the code into an unreadable mess.
http://gcc.gnu.org/onlinedocs/gcc-4....timize-Options
KashAI>> Now that is useful info. Just checked and found that VS 6.0 and Sun Workshop 6.0 also support lopp unrolling.
Sorry forgot one more thing regarding "1. unsigned int arithmatic is faster than signed int.
Where's your evidence?"
See http://lkml.org/lkml/2006/3/20/385
Where's your evidence?"
See http://lkml.org/lkml/2006/3/20/385
•
•
Join Date: Sep 2004
Posts: 3
Reputation:
Solved Threads: 0
When displaying output use printf every where posible over C++'s cout because of the of constructors to be initialized and series of cout class variable to be initialized and never ending list of inline codes to be executed
. If you want to see all this details try using <trace into> tool that ships with your IDE compiler and you will see what i mean.
. If you want to see all this details try using <trace into> tool that ships with your IDE compiler and you will see what i mean. •
•
Join Date: May 2006
Posts: 10
Reputation:
Solved Threads: 0
•
•
•
•
Originally Posted by thekashyap
2. I'm sure most ppl know this but writing as it's not already mentioned in this topic so far. Use unsigned int stored in registers for loop variables.
Reasons
•
•
•
•
2. registers are registers ! They're simply faster than memory access.
But, the register keyword can reduce performances on some compilers, because they interpret it as a strong request, from the programmer, to use a register for storage of the variable, which condemns one register.
Even on very old compilers where the register keyword was a useful hint, it would have been utterly stupid to use the register keyword everywhere, as it would be as slow, or slower, than using no keyword at all, because the compiler would not be better than using its default "guessing" algorithm.
The register keyword should be used only at places, where you want to give a hint to the compiler, that THIS variable needs to be accessed faster than other ones, even if it reduces performances of other variables.
•
•
•
•
1. unsigned int arithmatic is faster than signed int.
On two's complement machines, additions, substractions and multiplications have identical performances as signed or unsigned, since this is exactly the same operation.
For comparisons, the performances are identical on x86 architectures, since the same operation is used for all comparisons (cmp).
On all other architectures, there is absolutely nothing that would add a performance penalty on signed comparisons, because integer comparisons require only very very few transitors... The comparison itself, cannot require more than one CPU cycle.
For integer division, signed integer division was a bit slower than unsigned integer division on old CPU.
But, integer divisions are very rarely time critical, because division is not a very much used operation.
•
•
•
•
3. Optimizing the breaking conditions in for loops. If you know that the loop variable's range is from 0 to some +ve number AND it doesn't matter which way you traverse while looping, you can optimize the loop like this:
GCC 3.4.5 (-O2) for i386, is clever enough to optimize the first loop with a decrementation operation.
This is because, forward loops are very common, and GCC has specific optimizations for this type of code.
On the other hand, GCC 3.4.5 is not clever enough to produce good code for your "manually optimized" loop.
for( int i = 0; i <= 30; i++ );
Produces this assembly code (MinGW 3.4.5 for Win32 -O2):
C++ Syntax (Toggle Plain Text)
0x401300 : dec eax 0x401301 : jns 0x401300
But:
for( int i = 30; i--; );
Produces:
C++ Syntax (Toggle Plain Text)
0x401300 : dec eax 0x401301 : cmp eax,0xffffffff 0x401304 : jne 0x401300
Why this pessimization?
First, the following code:
C++ Syntax (Toggle Plain Text)
0x401300 : dec eax 0x401301 : js 0x401300
The compiler could have seen that all the values of i will be in range [0,30), but GCC is not clever enough to understand that, because you wrote a weird loop.
A good code, benefiting from the fact that "dec eax" sets the zf and sf flags, would require that you stop when i reaches zero, not -1.
Your code confuses the compiler, and is a pessimization.
So, don't do that!
Note:
C++ Syntax (Toggle Plain Text)
for( int i = 31; --i; );
C++ Syntax (Toggle Plain Text)
0x401300 : dec eax 0x401301 : jns 0x401300
•
•
•
•
4, Optimizing very small loops using switch-case.
When you know that the range of loop variable's value is
pretty small avoid the loop altogether.
Also, you should notice that, this should only be used on the most critical code, as it greatly increases the code size, which can have a serious performance penalty.
•
•
•
•
5. Another way of optimizing loops is to unroll it:
I benchmarked the two programs, using NUL as the standard output.
There is no sensible speed difference.
Both require 3900 milliseconds to execute on my computer.
A revelant piece of code of the two things:
C++ Syntax (Toggle Plain Text)
; without manual loop unrolling ; Assume a K6-2 CPU 0x401323 <main+67>: inc ebx 0x401324 <main+68>: push 0x403000 ;1 0x401329 <main+73>: call 0x4018a0 <printf> 0x40132e <main+78>: add esp,0x10 0x401331 <main+81>: cmp ebx,0xc350 ;1 0x401337 <main+87>: jl 0x401320 <main+64> ; 3 ; -> 3 CPU cycles + approximatively 39600 CPU cycles for the printf call (if the output stream is the NUL device).
C++ Syntax (Toggle Plain Text)
; with manual loop unrolling 0x40134d <main+109>: pop eax 0x40134e <main+110>: lea eax,[ebx+1] ;1 0x401351 <main+113>: pop edx ;2 0x401352 <main+114>: push eax ;3 0x401353 <main+115>: push 0x403000 ;4 0x401358 <main+120>: call 0x4019c0 <printf> ; -> 4 CPU cycles + approximatively 39600 CPU cycles for the printf call.
So, your "optimization", approximatively reduce performances by 0.0025%.
Which is negligible.
•
•
Join Date: May 2006
Posts: 10
Reputation:
Solved Threads: 0
•
•
•
•
When displaying output use printf every where posible over C++'s cout because of the of constructors to be initialized and series of cout class variable to be initialized and never ending list of inline codes to be executed . If you want to see all this details try using <trace into> tool that ships with your IDE compiler and you will see what i mean.
This is very highly compiler dependent.
For example, Borland C++ 5.0 is faster for cout than for printf.
Check my answer on this thread:
http://www.codeguru.com/forum/showthread.php?t=383112
And, don't forget that micro-optimizations are the ennemy of real optimizations.
•
•
Join Date: Apr 2007
Posts: 6
Reputation:
Solved Threads: 0
A performance tip that has served me well with C++, C#, Java, VB, and scripting languages is counting backwards. When using a comparison in a loop (presumably for termination purposes), if possible, count down to zero instead of up to a non-zero value.
Since every machine language in existence has "compare to zero" operators, smart compilers can utilize this efficiency.
Normally, the compiler saves the comparison value in memory and then accesses it indirectly for each loop. However, many compilers will recognize the comparison to zero and optimize it with a single machine language command, bne, bge, etc..
In complex, nested loops, the optimization can be amazing. The main down fall I've observed is compiler consistency. I have not observed .NET's IL doing this and it doesn't always do this when going native.
Since every machine language in existence has "compare to zero" operators, smart compilers can utilize this efficiency.
Normally, the compiler saves the comparison value in memory and then accesses it indirectly for each loop. However, many compilers will recognize the comparison to zero and optimize it with a single machine language command, bne, bge, etc..
In complex, nested loops, the optimization can be amazing. The main down fall I've observed is compiler consistency. I have not observed .NET's IL doing this and it doesn't always do this when going native.
•
•
Join Date: Jul 2007
Posts: 2
Reputation:
Solved Threads: 0
•
•
•
•
An easy way to swap 2 variables without using another variable:
C++ Syntax (Toggle Plain Text)
a=a+b; b=a-b; a=a-b;
I don't think so. the result will be the fllowigs:
a=b;
b=0;
I am a beginner
please give me some advice ![]() |
Similar Threads
- improve performance of the following io codes (C)
- Performance Improvements (Windows NT / 2000 / XP)
Other Threads in the C++ Forum
- Previous Thread: Help with an overloaded operator
- Next Thread: Combined accessor/mutator?
| Thread Tools | Search this Thread |
api array arrays beginner binary bitmap c++ c/c++ calculator char char* class classes coding compile compiler console conversion convert count data database delete desktop developer directshow dll dynamiccharacterarray email encryption error file forms fstream function functions game generator getline google graph homeworkhelper iamthwee ifstream input int integer java lib linkedlist linux list loop looping loops map math matrix memory multiple news node number numbertoword output parameter pointer problem program programming project proxy python random read recursion recursive reference return rpg sorting string strings struct template templates test text tree unix url vector video visualstudio win32 windows winsock word wordfrequency wxwidgets






