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

Python Programming | JNTUA | UNIT 2 | Fruitful Functions |
Python Programming | JNTUA | UNIT 2 | Fruitful Functions | Python Programming | JNTUA | UNIT 2 | Fruitful Functions |
Python Programming | JNTUA | UNIT 2 | Fruitful Functions | FabMinds
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree Divya Ks
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data StructureDharita Chokshi
 
Knapsack problem using dynamic programming
Knapsack problem using dynamic programmingKnapsack problem using dynamic programming
Knapsack problem using dynamic programmingkhush_boo31
 
Loops in c programming
Loops in c programmingLoops in c programming
Loops in c programmingCHANDAN KUMAR
 
Ai lecture 14(unit03)
Ai lecture  14(unit03)Ai lecture  14(unit03)
Ai lecture 14(unit03)vikas dhakane
 
Syntax-Directed Translation into Three Address Code
Syntax-Directed Translation into Three Address CodeSyntax-Directed Translation into Three Address Code
Syntax-Directed Translation into Three Address Codesanchi29
 
Knowledge representation and Predicate logic
Knowledge representation and Predicate logicKnowledge representation and Predicate logic
Knowledge representation and Predicate logicAmey Kerkar
 
14. Query Optimization in DBMS
14. Query Optimization in DBMS14. Query Optimization in DBMS
14. Query Optimization in DBMSkoolkampus
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaEdureka!
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesFahim Ferdous
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfzupsezekno
 
List comprehensions
List comprehensionsList comprehensions
List comprehensionsJordi Gómez
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 

What's hot (20)

Python Programming | JNTUA | UNIT 2 | Fruitful Functions |
Python Programming | JNTUA | UNIT 2 | Fruitful Functions | Python Programming | JNTUA | UNIT 2 | Fruitful Functions |
Python Programming | JNTUA | UNIT 2 | Fruitful Functions |
 
Lecture optimal binary search tree
Lecture optimal binary search tree Lecture optimal binary search tree
Lecture optimal binary search tree
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Python algorithm
Python algorithmPython algorithm
Python algorithm
 
Knapsack problem using dynamic programming
Knapsack problem using dynamic programmingKnapsack problem using dynamic programming
Knapsack problem using dynamic programming
 
Collision in Hashing.pptx
Collision in Hashing.pptxCollision in Hashing.pptx
Collision in Hashing.pptx
 
Loops in c programming
Loops in c programmingLoops in c programming
Loops in c programming
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
Complements
ComplementsComplements
Complements
 
Ai lecture 14(unit03)
Ai lecture  14(unit03)Ai lecture  14(unit03)
Ai lecture 14(unit03)
 
Syntax-Directed Translation into Three Address Code
Syntax-Directed Translation into Three Address CodeSyntax-Directed Translation into Three Address Code
Syntax-Directed Translation into Three Address Code
 
Knowledge representation and Predicate logic
Knowledge representation and Predicate logicKnowledge representation and Predicate logic
Knowledge representation and Predicate logic
 
14. Query Optimization in DBMS
14. Query Optimization in DBMS14. Query Optimization in DBMS
14. Query Optimization in DBMS
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | Edureka
 
LISP: Introduction to lisp
LISP: Introduction to lispLISP: Introduction to lisp
LISP: Introduction to lisp
 
BackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and ExamplesBackTracking Algorithm: Technique and Examples
BackTracking Algorithm: Technique and Examples
 
LeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdfLeetCode Solutions In Java .pdf
LeetCode Solutions In Java .pdf
 
List comprehensions
List comprehensionsList comprehensions
List comprehensions
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 

Viewers also liked

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 (17)

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

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Recently uploaded (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

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