Code Tuning Strategies and Techniques CS480 – Software Engineering II Azusa Pacific University Dr. Sheldon X. Liang.

Slides:



Advertisements
Similar presentations
Code Tuning Strategies and Techniques
Advertisements

Tori Bowman CSSE 375, Rose-Hulman October 22, Code Tuning (Chapters of Code Complete)
Code Optimization and Performance Chapter 5 CS 105 Tour of the Black Holes of Computing.
When and How to Improve Code Performance? Ivaylo Bratoev Telerik Corporation
Code Tuning Strategies and Techniques CS524 – Software Engineering Azusa Pacific University Dr. Sheldon X. Liang Mike Rickman.
1 Optimizing compilers Managing Cache Bercovici Sivan.
ECE 454 Computer Systems Programming Compiler and Optimization (I) Ding Yuan ECE Dept., University of Toronto
Programming Logic and Design, Third Edition Comprehensive
Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.
Quicksort CS 3358 Data Structures. Sorting II/ Slide 2 Introduction Fastest known sorting algorithm in practice * Average case: O(N log N) * Worst case:
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Computer Science 1620 Loops.
CS 536 Spring Intermediate Code. Local Optimizations. Lecture 22.
Analysis of Algorithms. Time and space To analyze an algorithm means: –developing a formula for predicting how fast an algorithm is, based on the size.
4/23/09Prof. Hilfinger CS 164 Lecture 261 IL for Arrays & Local Optimizations Lecture 26 (Adapted from notes by R. Bodik and G. Necula)
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Program Design and Development
 2007 Pearson Education, Inc. All rights reserved C Program Control.
Code Tuning Techniques CPSC 315 – Programming Studio Spring 2008 Most examples from Code Complete 2.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Code Tuning Techniques CPSC 315 – Programming Studio Fall 2009 Most examples from Code Complete 2.
ECE122 L17: Method Development and Testing April 5, 2007 ECE 122 Engineering Problem Solving with Java Lecture 17 Method Development and Testing.
Sorting II/ Slide 1 Lecture 24 May 15, 2011 l merge-sorting l quick-sorting.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Code-Tuning By Jacob Shattuck. Code size/complexity vs computation resource utilization A classic example: Bubblesort A classic example: Bubblesort const.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
Fundamentals of Python: From First Programs Through Data Structures
Data Structures Introduction Phil Tayco Slide version 1.0 Jan 26, 2015.
JS Arrays, Functions, Events Week 5 INFM 603. Agenda Arrays Functions Event-Driven Programming.
Fundamentals of Python: First Programs
5.3 Machine-Independent Compiler Features
Topic #10: Optimization EE 456 – Compiling Techniques Prof. Carl Sable Fall 2003.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Database Performance Tuning and Query Optimization.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Chapter 1 Introduction Dr. Frank Lee. 1.1 Why Study Compiler? To write more efficient code in a high-level language To provide solid foundation in parsing.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Chapter 25: Code-Tuning Strategies. Chapter 25  Code tuning is one way of improving a program’s performance, You can often find other ways to improve.
Software Construction and Evolution - CSSE 375 Code Tuning Shawn and Steve Left – Even tuning an ancient instrument like a violin involves multiple steps.
1 Code optimization “Code optimization refers to the techniques used by the compiler to improve the execution efficiency of the generated object code”
CS 3500 L Performance l Code Complete 2 – Chapters 25/26 and Chapter 7 of K&P l Compare today to 44 years ago – The Burroughs B1700 – circa 1974.
Outline Announcements: –HW III due Friday! –HW II returned soon Software performance Architecture & performance Measuring performance.
Lecture 7. Solution by Substitution Method T(n) = 2 T(n/2) + n Substitute n/2 into the main equation 2T(n/2) = 2(2(T(n/4)) + n/2) = 4T(n/4) + n And T(n)
Chapter 1 Computers, Compilers, & Unix. Overview u Computer hardware u Unix u Computer Languages u Compilers.
Introduction to programming Carl Smith National Certificate Year 2 – Unit 4.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Machine Independent Optimizations Topics Code motion Reduction in strength Common subexpression sharing.
Decision Making and Branching (cont.)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4 Loops.
DATA STRUCTURES (CS212D) Overview & Review Instructor Information 2  Instructor Information:  Dr. Radwa El Shawi  Room: 
P ROGRAMMING L OGIC GWDA123 Sharon Kaitner, M.Ed. Winter 2015: Week 2.
CS412/413 Introduction to Compilers and Translators April 2, 1999 Lecture 24: Introduction to Optimization.
Outline Announcements: –HW II Idue Friday! Validating Model Problem Software performance Measuring performance Improving performance.
CSC 212 – Data Structures Lecture 15: Big-Oh Notation.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Software Engineering Algorithms, Compilers, & Lifecycle.
©SoftMoore ConsultingSlide 1 Code Optimization. ©SoftMoore ConsultingSlide 2 Code Optimization Code generation techniques and transformations that result.
Optimization. How to Optimize Code Conventional Wisdom: 1.Don't do it 2.(For experts only) Don't do it yet.
Chapter 4 – C Program Control
Matrix 2015/11/18 Hongfei Yan zip(*a) is matrix transposition
Optimization Code Optimization ©SoftMoore Consulting.
Algorithm Analysis CSE 2011 Winter September 2018.
Unit# 9: Computer Program Development
Code Tuning Techniques
Optimization 薛智文 (textbook ch# 9) 薛智文 96 Spring.
Data Structures Introduction
Chapter 4: Writing and Designing a Complete Program
Presentation transcript:

Code Tuning Strategies and Techniques CS480 – Software Engineering II Azusa Pacific University Dr. Sheldon X. Liang

Code Tuning Strategies and Techniques  Overview  Performance and Code Tuning  Introduction to Code Tuning  Common Sources of Inefficiency  Measurement  Iteration  Code-Tuning Techniques  Checklist & Summary

Performance and Code Tuning cont. Operating-system interactions Inefficient operating system routines Compiler generated system calls Code compilation Good compilers optimize code speed Hardware New hardware may be cheaper than optimizing code Code tuning(Lastly) Practice of modifying correct code in ways that make it run more efficiently

Introduction to Code Tuning More lines of code = less efficient - FALSE You should optimize as you go – FALSE Make it work correctly first What do you want to tune for? Code Size versus Speed Use a worker thread The appearance of performance

Introduction to Code Tuning When to tune Jackson's Rules of Optimization: Rule 1. Don't do it. Rule 2 (for experts only). Don't do it yet—that is, not until you have a perfectly clear and unoptimized solution. —M. A. Jackson Use compiler optimization Write clear code Let the compiler to the optimizing

Common Sources of Inefficiency Input / Output Operations In memory operation much faster than disk access Organize and minimize I/O operations Paging Operation that causes the operating system to swap pages of memory is much slower than an operation that works on only one page of memory for ( column = 0; column < MAX_COLUMNS; column++ ) { for ( row = 0; row < MAX_ROWS; row++ ) { table[ row ][ column ] = BlankTableElement(); }} for ( row = 0; row < MAX_ROWS; row++ ) { for ( column = 0; column < MAX_COLUMNS; column++ ) { table[ row ][ column ] = BlankTableElement(); }}

Common Sources of Inefficiency System calls Calls to system routines are often expensive. Context Switch Possible Solutions Write your own services. Avoid going to the system. Work with the system vendor to make the call faster. Interpreted languages Interpreted languages exact significant performance penalties If performance matters, don’t use them

Measurement Measure your code to find the hot spots You don’t know if or how much your improving if you don’t measure Measurement needs to be precise QueryPerformanceCounter – Windows Only measure the code your tuning

Iteration Multiple techniques may be necessary Cumulative effect of tuning

Code-Tuning Techniques Logic Stop Testing When You Know the Answer negativeInputFound = false; for ( i = 0; i < count; i++ ) { if ( input[ i ] < 0 ) { negativeInputFound = true; break; } Consider order of evaluation if ( 5 < x ) and ( x < 10 ) then...

Code-Tuning Techniques Order Tests by Frequency Arrange tests so that the one that's fastest and most likely to be true is performed first 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

Code-Tuning Techniques Compare Performance of Similar Logic Structures Test from case statement versus if-then-else logic. Languagecaseif-then- else Time Savings Performance Ratio C# %1:1 Java %6:1 Visual Basic %1:4 This example illustrates the difficulty of performing any sort of "rule of thumb" to code tuning There is simply no reliable substitute for measuring results.

Code-Tuning Techniques Loops Minimizing the Work Inside Loops One key to writing effective loops is to minimize the work done inside a loop 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; }

Code-Tuning Techniques Loops Strength Reduction Reducing strength means replacing an expensive operation such as multiplication with a cheaper operation such as addition For i = 0 to saleCount – 1 commission( i ) = (i + 1) * revenue * baseCommission * discount Next incrementalCommission = revenue * baseCommission * discount cumulativeCommission = incrementalCommission For i = 0 to saleCount – 1 commission( i ) = cumulativeCommission cumulativeCommission = cumulativeCommission + incrementalCommission Next

Code-Tuning Techniques Use the Fewest Array Dimensions Possible Conventional wisdom maintains that multiple dimensions on arrays are expensive. If you can structure your data so that it's in a one-dimensional array rather than a two- dimensional or three-dimensional array, you might be able to save some time

Code-Tuning Techniques Minimize Array References Advantageous to minimize array accesses The reference to discount[ discountType ] doesn't change when discountLevel changes in the inner loop for ( discountType = 0; discountType < typeCount; discountType++ ) { for ( discountLevel = 0; discountLevel < levelCount; discountLevel++ ) { rate[ discountLevel ] = rate[ discountLevel ] * discount[ discountType ]; }

Code-Tuning Techniques Minimize Array References Move discount [discountType] out of the inner loop so that you'll have only one array access per execution of the outer loop for ( discountType = 0; discountType < typeCount; discountType++ ) { thisDiscount = discount[ discountType ]; for ( discountLevel = 0; discountLevel < levelCount; discountLevel++ ) { rate[ discountLevel ] = rate[ discountLevel ] * thisDiscount; }

Code-Tuning Techniques Use Caching Caching means saving a few values in such a way that you can retrieve the most commonly used values more easily than the less commonly used values You can cache the results of time-consuming computations too public double Hypotenuse( double sideA, double sideB ) { // check to see if the triangle is already in the cache if ( ( sideA == cachedSideA ) && ( sideB == cachedSideB ) ) { return cachedHypotenuse; } // compute new hypotenuse and cache it cachedHypotenuse = Math.sqrt( ( sideA * sideA ) + ( sideB * sideB ) ); cachedSideA = sideA; cachedSideB = sideB; return cachedHypotenuse; }

Code-Tuning Techniques Expressions Much of the work in a program is done inside mathematical or logical expressions. Complicated expressions tend to be expensive Exploit Algebraic Identities Use algebraic identities to replace costly operations with cheaper ones. The following expressions are logically equivalent: not a and not b not (a or b)

Code-Tuning Techniques Initialize at Compile Time If you're using a named constant or a magic number in a routine call, that's a clue that you could pre-compute the number unsigned int Log2( unsigned int x ) { return (unsigned int) ( log( x ) / log( 2 ) ); } Replace log(2) with a constant

Code-Tuning Techniques Eliminate Common Subexpressions If an expression is repeated several times, assign it to a variable rather than re-computing in several places. payment = loanAmount / (( Math.pow( ( interestRate / 12.0 ), -months ) ) / ( interestRate / 12.0 ) ); interestRate / 12.0 could be a variable

Code-Tuning Techniques Routines Good routine decomposition is best for well tuned code Small, well-defined routines save space Take the place of doing jobs separately in multiple places You can re-factor code in one routine and thus improve every routine that calls it Small routines are relatively easy to rewrite in a low-level language

Code-Tuning Techniques Routines Rewrite Routines Inline Code executes “in-place” versus calling a routine Less advantage with newer compilers and computers Recoding in a Low-Level Language If you're coding in C++, the low-level language might be assembler. If you're coding in Python, the low-level language might be C.

Summary of the Approach to Code Tuning 1.Develop the software by using well-designed code that's easy to understand and modify. 2.If performance is poor, a.Save a working version of the code so that you can get back to the "last known good state." b.Measure the system to find hot spots. c.Determine whether the weak performance comes from inadequate design, data types, or algorithms and whether code tuning is appropriate. If code tuning isn't appropriate, go back to step 1. d.Tune the bottleneck identified in step (c). e.Measure each improvement one at a time. f.If an improvement doesn't improve the code, revert to the code saved in step (a). (Typically, more than half the attempted tunings will produce only a negligible improvement in performance or degrade performance.) 3.Repeat from step 2.