C++ Footprint and Performance Optimization By R Alexander, G Bensley Publisher : Sams Publishing Pub Date : September 20, 2000 ISBN : 0-672-31904-7 Pages : 400 The market for miniature computer programming is exploding C++ Footprint and Performance Optimization supplies programmers the knowledge they need to write code for the increasing number of hand-held devices, wearable computers, and intelligent appliances This book gives readers valuable knowledge and programming techniques that are not currently part of traditional programming training Table of • Contents • Index In the world of C++ programming, all other things being equal, programs that are smaller and faster are better C++ Footprint and Performance Optimization contains case studies and sample code to give readers concrete examples and proven solutions to problems that don't have cut and paste solutions EEn 777 Copyright About the Authors Acknowledgments Tell Us What You Think! Introduction: Why Optimize? Aim of This Book Who This Book Is For The Structure of This Book Part I: Everything But the Code Chapter 1 Optimizing: What Is It All About? Performance Footprint Summary Chapter 2 Creating a New System System Requirements System Design Issues The Development Process Data Processing Methods Summary Chapter 3 Modifying an Existing System Identifying What to Modify Beginning Your Optimization Analyzing Target Areas Performing the Optimizations Summary Part II: Getting Our Hands Dirty Chapter 4 Tools and Languages Tools You Cannot Do Without Optimizing with Help from the Compiler The Language for the Job Summary Chapter 5 Measuring Time and Complexity The Marriage of Theory and Practice System Influences Summary Chapter 6 The Standard C/C++ Variables Variable Base Types Grouping Base Types Summary Chapter 7 Basic Programming Statements Selectors Loops Summary Chapter 8 Functions Invoking Functions Passing Data to Functions Early Returns Functions as Class Methods Summary Chapter 9 Efficient Memory Management Memory Fragmentation Memory Management Resizable Data Structures Summary Chapter 10 Blocks of Data Comparing Blocks of Data The Theory of Sorting Data Sorting Techniques Summary Chapter 11 Storage Structures Arrays Linked Lists Hash Tables Binary Trees Red/Black Trees Summary Chapter 12 Optimizing IO Efficient Screen Output Efficient Binary File IO Efficient Text File IO Summary Arithmetic Operations Operating System–Based Optimizations Summary Chapter 13 Optimizing Your Code Further Part III: Tips and Pitfalls Chapter 14 Tips Tricks Preparing for the Future Chapter 15 Pitfalls Algorithmic Pitfalls Typos that Compile Other Pitfalls Index Copyright Copyright © 2000 by Sams Publishing All rights reserved No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher No patent liability is assumed with respect to the use of the information contained herein Although every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions Nor is any liability assumed for damages resulting from the use of the information contained herein Library of Congress Catalog Card Number: 99-068917 Printed in the United States of America First Printing: September, 2000 02 01 00 4 3 2 1 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized Sams cannot attest to the accuracy of this information Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied The information provided is on an "as is" basis The authors and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the Web site or programs accompanying it Publisher Michael Stephens Acquisitions Editor William E Brown Development Editors Tony Amico Beverly Scherf Managing Editor Matt Purcell Project Editor Natalie F Harris Copy Editors Michael Dietsch Andrew Simmons Indexer Sandra Henselmeier Proofreaders Pat Kinyon Tony Reitz Matt Wynalda Technical Editor Greg Guntle Team Coordinator Pamalee Nelson Media Developer Dan Scherf Interior Designers Gary Adair Anne Jones Cover Designer Anne Jones Production Darin Crone Dedication To Olivera, Tjitske, and Leanne, who somehow found the restraint to not kill us About the Authors As the authors of the book you are about to read, we would like to introduce ourselves With more than 10 years of professional IT experience between us, we have worked on vastly different projects for different companies One of us is currently involved in designing timecritical embedded software, the other is working on Internet and satellitetransmission software for digital video communications In our spare time we have been working on a project which involved developing advanced techniques for optimizing C/C++ code for speed and size We found that while working on professional software, the same kinds of problems and pitfalls kept arising, whether during development of embedded software or even desktop applications It seemed to us that a deeper understanding of these problems could not only aid in writing better software, but also be of great assistance during fault solving That is why we decided that the result of our project should be a tutorial in which we share our findings of practical problems and the solutions we used, as well as our theories on optimizing software The book you are holding now is in fact one that we, and many of our colleagues, have been looking for since we started in the IT business R Alexander G Bensley Acknowledgments We would like to thank the people at Sams for recognizing the value of this project and helping us develop it into the book you are now holding Special thanks go to those on the home front who had to endure our absence and more than their fair share of duties around the house Tell Us What You Think! As the reader of this book, you are our most important critic and commentator We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way As a Publisher for Sams, I welcome your comments You can fax, email, or write me directly to let me know what you did or didn't like about this book—as well as what we can do to make our books stronger Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message When you write, please be sure to include this book's title and author as well as your name and phone or fax number I will carefully review your comments and share them with the author and editors who worked on the book Fax: Email: Mail: 317-581-4770 footprint@macmillanusa.com Michael Stephens Sams 201 West 103rd Street Indianapolis, IN 46290 USA stack frames inside functions stack memory heap memory comparing 2nd member variables code 2nd stacks with dedicated memory management code 2nd 3rd without dedicated memory management code 2nd 3rd 4th StackSpace standard pattern matching (data) 2nd Standard Template Library (STL) 2nd statements #include 2nd body case extern int fn() statement extern int fn(void) if else 2nd 3rd concatenating 2nd expressions 2nd 3rd 4th loop code to abort interations 2nd code to abort with a break 2nd code to abort with a flag 2nd mathematical and C/C++ comparing switch 2nd 3rd cases 2nd 3rd code statements [See also loop statements]2nd [See also selector statements] states program (multitasking) static application frameworks 2nd static information generated by compilers 2nd static parts calculations 2nd 3rd 4th 5th 6th 7th conversions 2nd 3rd 4th 5th 6th 7th Static Source Code Analyzer tool 2nd static value generation code 2nd statically binding methods inadvertently code 2nd statically bound methods mixing with dynamically bound methods 2nd status functions IO streams step into functions step out of functions step tool STL (Standard Template Library) storage data models 2nd storage requirements footprint size measuring 2nd memory footprint storing data 2nd 3rd 4th space required storing memory 2nd stream functions binary files code to read and writing 2nd 3rd 4th streaming classes streams binary files random access, code 2nd cout 2nd ifstream class 2nd 3rd 4th IO functions status functions ofstream class 2nd 3rd 4th string keys code 2nd string method char pointer method comparing string searches (data) case-insensitive fast 2nd 3rd 4th 5th 6th 7th 8th strings arrays code to write with putchar() function 2nd characters code 2nd comparing integer arrays macros fields code 2nd hex byte values, code to convert 2nd 3rd 4th integer string comparison code lengths calculating search lookup characters methin STL (Standard Template Library) substrings strstr function 2nd structures C/C++ variable base types 2nd 3rd 4th 5th code for sizes 2nd code for stuffing 2nd data footprint 2nd trees unions code to replace 2nd structures with bit fields C/C++ variable base types code 2nd structures without bit fields C/C++ variable base types code stuffing C/C++ variable base type structures code 2nd suballocators BigChunkStack class 2nd 3rd 4th DirtyMalloc 2nd freelist 2nd 3rd 4th 5th 6th MMs 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th Stack class 2nd 3rd subelements radix sort substitutions conditional 2nd macro 2nd symbolic 2nd substrings subsystems performance of 2nd sums of ranges code to determine 2nd 3rd 4th swap files Swap() function swapping function values switch statement 2nd switch statements cases 2nd 3rd code switching tasks 2nd symbolic substitution 2nd symbols Size Type symptoms of system problems 2nd system behavior timing system influences cache misses 2nd cache pages instruction cache 2nd separate data cache 2nd minimizing 2nd data cache misses 2nd instruction cache misses 2nd page faults 2nd 3rd OS overhead administering IO task switching 2nd page faults 2nd user interactions system requirements availability 2nd impact on footprint 2nd impact on performance 2nd concurrent resource usage 2nd performance targers setting 2nd stability 2nd impact on footprint 2nd impact on performance 2nd target systems choosing 2nd system resources performance of 2nd systems buffers 2nd data processing methods batch 2nd immediate 2nd periodic 2nd requests 2nd designing application frameworks (static) 2nd intermediate objects 2nd object lifetime (dynamic) 2nd 3rd 4th persistent objects 2nd spawned objects 2nd temporary objects 2nd endianness 2nd code to determing 2nd file portability 2nd footprint measurements, scheduling 2nd operating portability 2nd optimization beginning 2nd candidates, analyzing 2nd 3rd 4th candidates, analyzing and selecting 2nd candidates, data model processing candidates, data model storage 2nd candidates, data model transactions 2nd candidates, data models 2nd candidates, designing and implementing 2nd candidates, finding 2nd candidates, processing time excessive 2nd 3rd candidates, processing time predictable 2nd candidates, processing time reduced 2nd optimizing functionality, designing 2nd functionality, implementing 2nd functionality, replacing 2nd 3rd 4th 5th functionality, software 2nd functionality, tuning software 2nd 3rd OSs considerations 2nd performance measurements, scheduling 2nd problems symptoms 2nd prototyping 2nd 3rd responsiveness target choosing 2nd [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] tables C/C++ variable base type alignment hash 2nd 3rd 4th 5th deleting elements functions 2nd 3rd 4th 5th inserting elements 2nd searching elements sorting elements 2nd terminology traversing elements jump 2nd 3rd lookup set bits in data blocks, code to count VPTR (virtual table pointer) 2nd 3rd VT (virtual table) 2nd target systems choosing 2nd targets makefile 2nd code 2nd targets of performance setting 2nd task switching (multitasking) 2nd 3rd processes scheduling 2nd threads scheduling 2nd tasks performing 2nd switching 2nd techniques blocks of data sorting 2nd overlay for programs 2nd TemperatureUsingFreeList instances 2nd templates class methods 2nd 3rd 4th 5th code for misusing 2nd generic code 2nd of functions code 2nd temporary objects 2nd terminating zero (Ô Õ ) terminology hash tables trees test cases 2nd test results 07Source01.cpp program 2nd array lookup 2nd binary files IO screen output 2nd test.cc code compiler optimization testing programs 2nd text files IO 2nd configuration files 2nd data storage 2nd 3rd 4th pattern matching, code with CompareStr() function 2nd pattern matching, code with wildcards 2nd 3rd searching 2nd searching with wildcards 2nd 3rd 4th 5th TextFile class 2nd 3rd lookup characters no thing as vague as something strings code to find characters 2nd code to get fields 2nd TextFile class 2nd 3rd interface the clock() function 2nd theories blocks of data sorting 2nd memory management 2nd 3rd 4th 5th 6th 7th Red/Black trees inserting elements 2nd threaded binary trees in-order traverse function code 2nd threads device interaction code 2nd multitasking 2nd 3rd 4th reading simultaneously code 2nd under UNIX code to create threads (task switching) scheduling 2nd TIME macro code 2nd time_fn() function 2nd 3rd 4th timer callback function code 2nd timing database sorting system behavior timing data for inheritance 2nd timing function 2nd 3rd 4th implementing code 2nd source code location timing functions Mul/Shift code 2nd 3rd timing results function calling techniques tools assembler 2nd 3rd compiler 2nd 3rd debugger 2nd breakpoint calling stack conditional breakpoint continue function stack run step step into functions step out of functions watch debugging side effects 2nd Developer Studio accessing information sources linker 2nd Make utility 2nd 3rd preprocessor #include statements 2nd conditional substitution 2nd macro substitution 2nd symbolic substitution 2nd profiler 2nd 3rd 4th 5th programs testing 2nd runtime checker 2nd Static Source Code Analyzer 2nd transactions data models 2nd traversing binary trees 2nd 3rd 4th in-order 2nd post-order 2nd pre-order 2nd traversing elements in arrays traversing elements in linked lists traversing Red/Black trees trees binary 2nd 3rd deleting elements 2nd in-order traversing 2nd inserting elements 2nd 3rd nodes, code to search for 2nd ordered dat _ XE Ịdata;ordered;binary treesĨ XE Ịordered data;binary treesĨ post-order traversing 2nd pre-order traversing 2nd random ordered dat _ XE Ịdata;random ordered;binary treesĨ XE Ịrandom ordered data;binary trees searching elements 2nd shapes sorting elements 2nd threaded traversing 2nd 3rd 4th Red/Black 2nd 3rd code to rebalance 2nd 3rd 4th deleting elements 2nd inserting elements 2nd 3rd inserting elements theory 2nd inserting with a red parent and a black uncle rebalancing 2nd 3rd 4th searching elements sorting elements traversing structure terminology trees; traversing elements in hash tables two-step merge sorts Type symbol types vendor specific 2nd typo pitfalls bound methods mixing 2nd comments creating inadvertently 2nd labels creating inadvertently 2nd loop problems 2nd statements mathematical and C/C++, comparing X power of 2nd X between Y and Z 2nd typos wrong calculation performed code 2nd wrong methods called code 2nd tuning software 2nd 3rd [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] unions C/C++ variable base types 2nd 3rd 4th code for database fields 2nd code for size matching 2nd code for structures replacing 2nd UniversalSwap() function UNIX processes code to create threads code to create unnecessary checks code 2nd code to avoid 2nd unrolling loops 2nd unrolling loops upgrades for programs 2nd user interfaces illogical setup 2nd user-defined date keys code 2nd users interactions with system learning curves 2nd program performance views of 2nd programs ideal characteristics 2nd using C/C++ variables 2nd using programs long-term problems 2nd utilities Make 2nd 3rd [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] value versus reference passing data to functions 2nd 3rd values bytes converting to ASCII 2nd 3rd of functions swapping values in bit fields C/C++ variable base types code 2nd variable number of arguments 2nd 3rd 4th functions code to call 2nd code to implement 2nd variables heap memory members code 2nd stack memory members code 2nd variables [See also C/C++ variables] vendor specifics 2nd virtual functions calling 2nd class methods 2nd 3rd 4th 5th 6th VPTR (virtual table pointer) 2nd 3rd VT (virtual table) 2nd virtual keyword 2nd virtual memory management 2nd virtual PrintName function code 2nd virtual table (VT) 2nd virtual table pointer (VPTR) 2nd 3rd Visual Basic programming language characteristics 2nd volatile pointer code 2nd VPTR (virtual table pointer) 2nd 3rd VT (virtual table) 2nd [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] waiting times (multitasking) 2nd waiting times unexplained 2nd Web sites Sams Publishing code samples wildcards pattern matching watch tool code 2nd 3rd text files searching 2nd 3rd 4th 5th Windows processes code to create 2nd shared resources code to protect 2nd 3rd working memory programs footprint 2nd Worst Fit method 2nd wrap around of loop counters pitfalls 2nd writing binary files code for FILE functions 2nd code using ifstream class 2nd code using ofstream class 2nd code using stream functions 2nd 3rd 4th [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] X power of 2nd X between Y and Z pitfalls 2nd [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Z] zeros terminating (Ô Õ) ... machines, electric razors, thermostats, microwave ovens, cars, TVs, monitors and so on Obviously these examples span many different kinds of architectures and use a variety of microprocessors Different optimization techniques for performance and footprint size are needed... It shows where and why problems are likely to occur and offers ready-to-use solutions for efficient function calling, memory management, IO, and setting up and handling data structures Part III, "Tips and Pitfalls" (Chapters 14 and 15)—This third book part... IN THIS CHAPTER Performance Footprint This chapter provides an extensive introduction to optimization It explains the definitions and jargon used and clarifies why it is so important to know when and how to optimize software