SlideShare a Scribd company logo
11
Most read
17
Most read
21
Most read
Code-Tuning Techniques

Code Complete
Author : Steven C. McConnell.

Prof. Asha N

1
Code-Tuning Techniques




To improve performance in code
Also called as “anti-refactoring”.
Code tuning refers to small-scale changes
rather than changes in larger-scale designs.

Prof. Asha N

2
Code-Tuning Techniques
1.
2.
3.

4.
5.
6.

Logic
Loops
Data Transformations
Expressions
Routines
Recoding in Assembler

Prof. Asha N

3
1. Logic


Stop Testing When You Know the Answer
 if ( 5 < x ) and ( x < 10 ) then ...
With short-circuit evaluation
if ( 5 < x ) then
if ( x < 10 ) then ...


C++ Example of Not Stopping After You Know the Answer
negativeInputFound = False;
for ( i = 0; i < iCount; i++ )
{
if ( input[ i ] < 0 ) {
negativeInputFound = True;
}
}
Prof. Asha N

4
Contd….


Order Tests by Frequency




Arrange tests so that the one that’s fastest and most likely to be true is
performed first. This principle applies to case statements and to chains of ifthen-elses.
Visual Basic Example of a Poorly Ordered Logical Test
Select inputCharacter
Case "+", "="
ProcessMathSymbol( inputCharacter )
Case "0" To "9"
ProcessDigit( inputCharacter )
Case ",", ".", ":", ";", "!", "?"
ProcessPunctuation( inputCharacter )
Case " "
ProcessSpace( inputCharacter )
Case "A" To "Z", "a" To "z"
ProcessAlpha( inputCharacter )
Case Else
ProcessError( inputCharacter )
End Select

Prof. Asha N

5
Contd….


Visual Basic Example of a Well-Ordered Logical Test
Select inputCharacter
Case "A" To "Z", "a" To "z"
ProcessAlpha( inputCharacter )
Case " "
ProcessSpace( inputCharacter )
Case ",", ".", ":", ";", "!", "?"
ProcessPunctuation( inputCharacter )
Case "0" To "9"
ProcessDigit( inputCharacter )
Case "+", "="
ProcessMathSymbol( inputCharacter )
Case Else
ProcessError( inputCharacter )
End Select
Prof. Asha N

6
Contd….


Substitute Table Lookups for Complicated Expressions

Prof. Asha N

7
Contd….
C++ Example of a Complicated Chain of Logic
if ( ( a && !c ) || ( a && b && c ) ) {
category = 1;
}
else if ( ( b && !a ) || ( a && c && !b ) ) {
category = 2;
}
else if ( c && !a && !b ) {
category = 3;
}
else {
category = 0;
}
Prof. Asha N

8
Contd….
C++ Example of Using a Table Lookup to Replace Complicated
Logic

Prof. Asha N

9
Contd….


Use Lazy Evaluation
 Lazy evaluation is similar to just-in-time strategies
that do the work closest to when it’s needed.

Prof. Asha N

10
2. Loops









Un switching
Jamming
Unrolling
Minimizing the Work Inside Loops
Sentinel Values
Putting the Busiest Loop on the Inside
Strength Reduction

Prof. Asha N

11
Contd….


Un switching


putting loops inside the conditional rather than
putting the conditional inside the loop
C++ Example of a Switched Loop

Prof. Asha N

12
Contd….
C++ Example of an Unswitched Loop

Prof. Asha N

13
Contd….


Jamming
 Jamming, or “fusion,” is the result of combining two loops that
operate on the same set of elements. The gain lies in cutting the
loop overhead from two loops to one.




For i = 0 to employeeCount - 1
employeeName( i ) = ""
Next
...
For i = 0 to employeeCount - 1
employeeEarnings( i ) = 0
Next
For i = 0 to employeeCount - 1
employeeName( i ) = ""
employeeEarnings( i ) = 0
Next
Prof. Asha N

14
Contd….


Unrolling


The goal of loop unrolling is to reduce the amount of loop housekeeping




Java Example of a Loop That Can Be Unrolled
i = 0;
while ( i < count ) {
a[ i ] = i;
i = i + 1;
}

Java Example of a Loop That’s Been Unrolled Once
i = 0;
while ( i < count - 1 ) {
a[ i ] = i;
a[ i + 1 ] = i + 1;
i = i + 2;
}
if ( i == count ) {
a[ count - 1 ] = count - 1;
}

Prof. Asha N

15
Contd….


Minimizing the Work Inside Loops




for ( i = 0; i < rateCount; i++ ) {
netRate[ i ] = baseRate[ i ] * rates->discounts->factors->net;
}
quantityDiscount = rates->discounts->factors->net;
for ( i = 0; i < rateCount; i++ ) {
netRate[ i ] = baseRate[ i ] * quantityDiscount;
}

Prof. Asha N

16
Contd….


Sentinel Values
 When you have a loop with a compound test, you can often save
time by simplifying the test
found = FALSE;
i = 0;
while ( ( !found ) && ( i < count ) ) {
if ( item[ i ] == testValue ) {
found = TRUE;
}
else {
i++;
}
}
if ( found ) {
...
Prof. Asha N

17
Contd….


Putting the Busiest Loop on the Inside
for ( column = 0; column < 100; column++ ) {
for ( row = 0; row < 5; row++ ) {
sum = sum + table[ row ][ column ];
}
}

Prof. Asha N

18
Contd….


Strength Reduction


Reducing strength means replacing an expensive
operation such as multiplication with a cheaper
operation such as addition

Prof. Asha N

19
3. Data Transformations








Use Integers Rather Than Floating-Point
Numbers
Use the Fewest Array Dimensions
Possible
Minimize Array References
Use Supplementary Indexes
String-Length Index
Independent, Parallel Index Structure
Use Caching
Prof. Asha N

20
4. Expressions









Exploit Algebraic Identities
Use Strength Reduction
Initialize at Compile Time
Be Wary of System Routines
Use the Correct Type of Constants
Precompute Results
Eliminate Common Subexpressions

Prof. Asha N

21
5. Routines



the most powerful tools in code tuning is a
good routine decomposition
Rewrite Routines In Line

Prof. Asha N

22
6. Recoding in Assembler



Recoding in assembler tends to improve both speed
and code size
typical approach to optimizing with assembler
1. Write 100 percent of an application in a high-level language.
2. Fully test the application, and verify that it’s correct.
3. If performance improvements are needed after that, profile the
application to identify hot spots. Since about 5 percent of a
program usually accounts for about 50 percent of the running
time, you can usually identify small pieces of the program as
hot spots.
4. Recode a few small pieces in assembler to improve overall
performance.
Prof. Asha N

23

More Related Content

PPTX
PPT.pptx
PPTX
6 настай хүүхдийн нас сэтгэхүйн онцлог
PPTX
Glass ionomer cement
PPT
African Geography
PPSX
Russia presentation
PDF
Folic acid- Chemistry, One carbon metabolism and megaloblastic anemia
PPTX
Diabetes Mellitus
PPTX
Hypertension
PPT.pptx
6 настай хүүхдийн нас сэтгэхүйн онцлог
Glass ionomer cement
African Geography
Russia presentation
Folic acid- Chemistry, One carbon metabolism and megaloblastic anemia
Diabetes Mellitus
Hypertension

What's hot (20)

PPT
Code Tuning
PDF
Code tuning strategies
PPTX
Lexical analysis - Compiler Design
PPT
Unit 1 chapter 1 Design and Analysis of Algorithms
PDF
Ai lab manual
PPT
Trees
PPT
Divide and conquer
PDF
Daa notes 1
PPT
Dinive conquer algorithm
PPT
BackTracking Algorithm: Technique and Examples
PPTX
Code Optimization
PPTX
State space search and Problem Solving techniques
PDF
Lecture 01 introduction to compiler
PPTX
Linked list
PDF
Garbage Collection
PPT
Turing Machine
PDF
I. AO* SEARCH ALGORITHM
PPTX
Code generation
PDF
Multithreading
PPTX
Phases of Compiler
Code Tuning
Code tuning strategies
Lexical analysis - Compiler Design
Unit 1 chapter 1 Design and Analysis of Algorithms
Ai lab manual
Trees
Divide and conquer
Daa notes 1
Dinive conquer algorithm
BackTracking Algorithm: Technique and Examples
Code Optimization
State space search and Problem Solving techniques
Lecture 01 introduction to compiler
Linked list
Garbage Collection
Turing Machine
I. AO* SEARCH ALGORITHM
Code generation
Multithreading
Phases of Compiler
Ad

Viewers also liked (17)

PPT
A Guideline to Test Your Own Code - Developer Testing
PDF
Design in construction
PPTX
Java scriptcore brief introduction
PPTX
程序员实践之路
PPT
代码大全(内训)
PDF
Coding Style
PDF
Defencive programming
PDF
程序员发展漫谈
PDF
MOST_OpenFoundry_version control system_Git
PDF
Design in construction
PPTX
Variables
PDF
Integration
PDF
高品質軟體的基本動作 101 + 102 for NUU
PDF
高品質軟體的基本動作 101 for NTHU
PDF
The pseudocode
PPT
Rm 1 Intro Types Research Process
A Guideline to Test Your Own Code - Developer Testing
Design in construction
Java scriptcore brief introduction
程序员实践之路
代码大全(内训)
Coding Style
Defencive programming
程序员发展漫谈
MOST_OpenFoundry_version control system_Git
Design in construction
Variables
Integration
高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 for NTHU
The pseudocode
Rm 1 Intro Types Research Process
Ad

Similar to Code tuning techniques (20)

PDF
Algorithm Design and Analysis
ZIP
.Net 4.0 Threading and Parallel Programming
PPTX
DS Unit-1.pptx very easy to understand..
PPT
Data Structures- Part1 overview and review
PPTX
Lecture 02: Preliminaries of Data structure
PDF
Optimization in Programming languages
PPTX
Parallel and Async Programming With C#
PPT
Profiling and optimization
PDF
Chap 5 c++
PPT
Analysis.ppt
PDF
Oct.22nd.Presentation.Final
PDF
Effective Numerical Computation in NumPy and SciPy
PPTX
Computational Complexity.pptx
PPTX
Analysis of Algorithms_Under Graduate Class Slide
PPTX
Computer programming 2 Lesson 10
PPTX
Functional Programming in Swift
PPTX
Lecture 5Arrays on c++ for Beginner.pptx
PPT
Cis435 week01
PPTX
Lecture-5_Arrays.pptx FOR EDUCATIONAL PURPOSE
PPTX
COM1407: Arrays
Algorithm Design and Analysis
.Net 4.0 Threading and Parallel Programming
DS Unit-1.pptx very easy to understand..
Data Structures- Part1 overview and review
Lecture 02: Preliminaries of Data structure
Optimization in Programming languages
Parallel and Async Programming With C#
Profiling and optimization
Chap 5 c++
Analysis.ppt
Oct.22nd.Presentation.Final
Effective Numerical Computation in NumPy and SciPy
Computational Complexity.pptx
Analysis of Algorithms_Under Graduate Class Slide
Computer programming 2 Lesson 10
Functional Programming in Swift
Lecture 5Arrays on c++ for Beginner.pptx
Cis435 week01
Lecture-5_Arrays.pptx FOR EDUCATIONAL PURPOSE
COM1407: Arrays

Recently uploaded (20)

PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Cell Types and Its function , kingdom of life
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PPTX
Presentation on HIE in infants and its manifestations
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Final Presentation General Medicine 03-08-2024.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Anesthesia in Laparoscopic Surgery in India
Supply Chain Operations Speaking Notes -ICLT Program
102 student loan defaulters named and shamed – Is someone you know on the list?
Cell Types and Its function , kingdom of life
2.FourierTransform-ShortQuestionswithAnswers.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
human mycosis Human fungal infections are called human mycosis..pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Presentation on HIE in infants and its manifestations
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
RMMM.pdf make it easy to upload and study
VCE English Exam - Section C Student Revision Booklet
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...

Code tuning techniques

  • 1. Code-Tuning Techniques Code Complete Author : Steven C. McConnell. Prof. Asha N 1
  • 2. Code-Tuning Techniques    To improve performance in code Also called as “anti-refactoring”. Code tuning refers to small-scale changes rather than changes in larger-scale designs. Prof. Asha N 2
  • 4. 1. Logic  Stop Testing When You Know the Answer  if ( 5 < x ) and ( x < 10 ) then ... With short-circuit evaluation if ( 5 < x ) then if ( x < 10 ) then ...  C++ Example of Not Stopping After You Know the Answer negativeInputFound = False; for ( i = 0; i < iCount; i++ ) { if ( input[ i ] < 0 ) { negativeInputFound = True; } } Prof. Asha N 4
  • 5. Contd….  Order Tests by Frequency   Arrange tests so that the one that’s fastest and most likely to be true is performed first. This principle applies to case statements and to chains of ifthen-elses. Visual Basic Example of a Poorly Ordered Logical Test Select inputCharacter Case "+", "=" ProcessMathSymbol( inputCharacter ) Case "0" To "9" ProcessDigit( inputCharacter ) Case ",", ".", ":", ";", "!", "?" ProcessPunctuation( inputCharacter ) Case " " ProcessSpace( inputCharacter ) Case "A" To "Z", "a" To "z" ProcessAlpha( inputCharacter ) Case Else ProcessError( inputCharacter ) End Select Prof. Asha N 5
  • 6. Contd….  Visual Basic Example of a Well-Ordered Logical Test Select inputCharacter Case "A" To "Z", "a" To "z" ProcessAlpha( inputCharacter ) Case " " ProcessSpace( inputCharacter ) Case ",", ".", ":", ";", "!", "?" ProcessPunctuation( inputCharacter ) Case "0" To "9" ProcessDigit( inputCharacter ) Case "+", "=" ProcessMathSymbol( inputCharacter ) Case Else ProcessError( inputCharacter ) End Select Prof. Asha N 6
  • 7. Contd….  Substitute Table Lookups for Complicated Expressions Prof. Asha N 7
  • 8. Contd…. C++ Example of a Complicated Chain of Logic if ( ( a && !c ) || ( a && b && c ) ) { category = 1; } else if ( ( b && !a ) || ( a && c && !b ) ) { category = 2; } else if ( c && !a && !b ) { category = 3; } else { category = 0; } Prof. Asha N 8
  • 9. Contd…. C++ Example of Using a Table Lookup to Replace Complicated Logic Prof. Asha N 9
  • 10. Contd….  Use Lazy Evaluation  Lazy evaluation is similar to just-in-time strategies that do the work closest to when it’s needed. Prof. Asha N 10
  • 11. 2. Loops        Un switching Jamming Unrolling Minimizing the Work Inside Loops Sentinel Values Putting the Busiest Loop on the Inside Strength Reduction Prof. Asha N 11
  • 12. Contd….  Un switching  putting loops inside the conditional rather than putting the conditional inside the loop C++ Example of a Switched Loop Prof. Asha N 12
  • 13. Contd…. C++ Example of an Unswitched Loop Prof. Asha N 13
  • 14. Contd….  Jamming  Jamming, or “fusion,” is the result of combining two loops that operate on the same set of elements. The gain lies in cutting the loop overhead from two loops to one.   For i = 0 to employeeCount - 1 employeeName( i ) = "" Next ... For i = 0 to employeeCount - 1 employeeEarnings( i ) = 0 Next For i = 0 to employeeCount - 1 employeeName( i ) = "" employeeEarnings( i ) = 0 Next Prof. Asha N 14
  • 15. Contd….  Unrolling  The goal of loop unrolling is to reduce the amount of loop housekeeping   Java Example of a Loop That Can Be Unrolled i = 0; while ( i < count ) { a[ i ] = i; i = i + 1; } Java Example of a Loop That’s Been Unrolled Once i = 0; while ( i < count - 1 ) { a[ i ] = i; a[ i + 1 ] = i + 1; i = i + 2; } if ( i == count ) { a[ count - 1 ] = count - 1; } Prof. Asha N 15
  • 16. Contd….  Minimizing the Work Inside Loops   for ( i = 0; i < rateCount; i++ ) { netRate[ i ] = baseRate[ i ] * rates->discounts->factors->net; } quantityDiscount = rates->discounts->factors->net; for ( i = 0; i < rateCount; i++ ) { netRate[ i ] = baseRate[ i ] * quantityDiscount; } Prof. Asha N 16
  • 17. Contd….  Sentinel Values  When you have a loop with a compound test, you can often save time by simplifying the test found = FALSE; i = 0; while ( ( !found ) && ( i < count ) ) { if ( item[ i ] == testValue ) { found = TRUE; } else { i++; } } if ( found ) { ... Prof. Asha N 17
  • 18. Contd….  Putting the Busiest Loop on the Inside for ( column = 0; column < 100; column++ ) { for ( row = 0; row < 5; row++ ) { sum = sum + table[ row ][ column ]; } } Prof. Asha N 18
  • 19. Contd….  Strength Reduction  Reducing strength means replacing an expensive operation such as multiplication with a cheaper operation such as addition Prof. Asha N 19
  • 20. 3. Data Transformations        Use Integers Rather Than Floating-Point Numbers Use the Fewest Array Dimensions Possible Minimize Array References Use Supplementary Indexes String-Length Index Independent, Parallel Index Structure Use Caching Prof. Asha N 20
  • 21. 4. Expressions        Exploit Algebraic Identities Use Strength Reduction Initialize at Compile Time Be Wary of System Routines Use the Correct Type of Constants Precompute Results Eliminate Common Subexpressions Prof. Asha N 21
  • 22. 5. Routines   the most powerful tools in code tuning is a good routine decomposition Rewrite Routines In Line Prof. Asha N 22
  • 23. 6. Recoding in Assembler   Recoding in assembler tends to improve both speed and code size typical approach to optimizing with assembler 1. Write 100 percent of an application in a high-level language. 2. Fully test the application, and verify that it’s correct. 3. If performance improvements are needed after that, profile the application to identify hot spots. Since about 5 percent of a program usually accounts for about 50 percent of the running time, you can usually identify small pieces of the program as hot spots. 4. Recode a few small pieces in assembler to improve overall performance. Prof. Asha N 23