SlideShare a Scribd company logo
1 of 23
Download to read offline
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

What's hot (20)

Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Tsp branch and-bound
Tsp branch and-boundTsp branch and-bound
Tsp branch and-bound
 
Daa
DaaDaa
Daa
 
Elements of Dynamic Programming
Elements of Dynamic ProgrammingElements of Dynamic Programming
Elements of Dynamic Programming
 
Find Transitive closure of a Graph Using Warshall's Algorithm
Find Transitive closure of a Graph Using Warshall's AlgorithmFind Transitive closure of a Graph Using Warshall's Algorithm
Find Transitive closure of a Graph Using Warshall's Algorithm
 
Asymptotic notations
Asymptotic notationsAsymptotic notations
Asymptotic notations
 
Lower bound
Lower boundLower bound
Lower bound
 
Church Turing Thesis
Church Turing ThesisChurch Turing Thesis
Church Turing Thesis
 
Strings
StringsStrings
Strings
 
Regular expression to NFA (Nondeterministic Finite Automata)
Regular expression to NFA (Nondeterministic Finite Automata)Regular expression to NFA (Nondeterministic Finite Automata)
Regular expression to NFA (Nondeterministic Finite Automata)
 
PROLOG: Introduction To Prolog
PROLOG: Introduction To PrologPROLOG: Introduction To Prolog
PROLOG: Introduction To Prolog
 
Modular programming
Modular programmingModular programming
Modular programming
 
Tsp branch and bound
Tsp branch and boundTsp branch and bound
Tsp branch and bound
 
Daa unit 1
Daa unit 1Daa unit 1
Daa unit 1
 
Introduction to prolog
Introduction to prologIntroduction to prolog
Introduction to prolog
 
Algorithm analysis
Algorithm analysisAlgorithm analysis
Algorithm analysis
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Brute force method
Brute force methodBrute force method
Brute force method
 
Automata theory - CFG and normal forms
Automata theory - CFG and normal formsAutomata theory - CFG and normal forms
Automata theory - CFG and normal forms
 
Merge Sort
Merge SortMerge Sort
Merge Sort
 

Viewers also liked

Code tuning strategies
Code tuning strategiesCode tuning strategies
Code tuning strategiesAsha Sari
 
A Guideline to Test Your Own Code - Developer Testing
A Guideline to Test Your Own Code - Developer TestingA Guideline to Test Your Own Code - Developer Testing
A Guideline to Test Your Own Code - Developer TestingFolio3 Software
 
Design in construction
Design in constructionDesign in construction
Design in constructionAsha Sari
 
Java scriptcore brief introduction
Java scriptcore brief introductionJava scriptcore brief introduction
Java scriptcore brief introductionHorky Chen
 
程序员实践之路
程序员实践之路程序员实践之路
程序员实践之路Horky Chen
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)Horky Chen
 
Defencive programming
Defencive programmingDefencive programming
Defencive programmingAsha Sari
 
程序员发展漫谈
程序员发展漫谈程序员发展漫谈
程序员发展漫谈Horky Chen
 
MOST_OpenFoundry_version control system_Git
MOST_OpenFoundry_version control system_GitMOST_OpenFoundry_version control system_Git
MOST_OpenFoundry_version control system_GitSu Jan
 
Design in construction
Design in constructionDesign in construction
Design in constructionAsha Sari
 
高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUUSu Jan
 
高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHU高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHUSu Jan
 
The pseudocode
The pseudocodeThe pseudocode
The pseudocodeAsha Sari
 
Rm 1 Intro Types Research Process
Rm   1   Intro Types   Research ProcessRm   1   Intro Types   Research Process
Rm 1 Intro Types Research Processitsvineeth209
 

Viewers also liked (18)

Code tuning strategies
Code tuning strategiesCode tuning strategies
Code tuning strategies
 
A Guideline to Test Your Own Code - Developer Testing
A Guideline to Test Your Own Code - Developer TestingA Guideline to Test Your Own Code - Developer Testing
A Guideline to Test Your Own Code - Developer Testing
 
Design in construction
Design in constructionDesign in construction
Design in construction
 
Java scriptcore brief introduction
Java scriptcore brief introductionJava scriptcore brief introduction
Java scriptcore brief introduction
 
程序员实践之路
程序员实践之路程序员实践之路
程序员实践之路
 
代码大全(内训)
代码大全(内训)代码大全(内训)
代码大全(内训)
 
Coding Style
Coding StyleCoding Style
Coding Style
 
Defencive programming
Defencive programmingDefencive programming
Defencive programming
 
程序员发展漫谈
程序员发展漫谈程序员发展漫谈
程序员发展漫谈
 
MOST_OpenFoundry_version control system_Git
MOST_OpenFoundry_version control system_GitMOST_OpenFoundry_version control system_Git
MOST_OpenFoundry_version control system_Git
 
Design in construction
Design in constructionDesign in construction
Design in construction
 
Variables
VariablesVariables
Variables
 
Integration
IntegrationIntegration
Integration
 
高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU高品質軟體的基本動作 101 + 102 for NUU
高品質軟體的基本動作 101 + 102 for NUU
 
高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHU高品質軟體的基本動作 101 for NTHU
高品質軟體的基本動作 101 for NTHU
 
Code Complete
Code CompleteCode Complete
Code Complete
 
The pseudocode
The pseudocodeThe pseudocode
The pseudocode
 
Rm 1 Intro Types Research Process
Rm   1   Intro Types   Research ProcessRm   1   Intro Types   Research Process
Rm 1 Intro Types Research Process
 

Similar to Code tuning techniques

.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel ProgrammingAlex Moore
 
DS Unit-1.pptx very easy to understand..
DS Unit-1.pptx very easy to understand..DS Unit-1.pptx very easy to understand..
DS Unit-1.pptx very easy to understand..KarthikeyaLanka1
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and reviewAbdullah Al-hazmy
 
Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureNurjahan Nipa
 
Optimization in Programming languages
Optimization in Programming languagesOptimization in Programming languages
Optimization in Programming languagesAnkit Pandey
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#Rainer Stropek
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyKimikazu Kato
 
Computational Complexity.pptx
Computational Complexity.pptxComputational Complexity.pptx
Computational Complexity.pptxEnosSalar
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in SwiftSaugat Gautam
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxarjurakibulhasanrrr7
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptSourabhPal46
 

Similar to Code tuning techniques (20)

Algorithm Design and Analysis
Algorithm Design and AnalysisAlgorithm Design and Analysis
Algorithm Design and Analysis
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 
DS Unit-1.pptx very easy to understand..
DS Unit-1.pptx very easy to understand..DS Unit-1.pptx very easy to understand..
DS Unit-1.pptx very easy to understand..
 
Data Structures- Part1 overview and review
Data Structures- Part1 overview and reviewData Structures- Part1 overview and review
Data Structures- Part1 overview and review
 
Lecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structureLecture 02: Preliminaries of Data structure
Lecture 02: Preliminaries of Data structure
 
Optimization in Programming languages
Optimization in Programming languagesOptimization in Programming languages
Optimization in Programming languages
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Analysis.ppt
Analysis.pptAnalysis.ppt
Analysis.ppt
 
Oct.22nd.Presentation.Final
Oct.22nd.Presentation.FinalOct.22nd.Presentation.Final
Oct.22nd.Presentation.Final
 
Effective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPyEffective Numerical Computation in NumPy and SciPy
Effective Numerical Computation in NumPy and SciPy
 
Computational Complexity.pptx
Computational Complexity.pptxComputational Complexity.pptx
Computational Complexity.pptx
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
Lecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptxLecture 5Arrays on c++ for Beginner.pptx
Lecture 5Arrays on c++ for Beginner.pptx
 
Cis435 week01
Cis435 week01Cis435 week01
Cis435 week01
 
COM1407: Arrays
COM1407: ArraysCOM1407: Arrays
COM1407: Arrays
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
lec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.pptlec_4_data_structures_and_algorithm_analysis.ppt
lec_4_data_structures_and_algorithm_analysis.ppt
 

Recently uploaded

Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 

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