Administration: Upcoming Due Dates Milestone 1: due Monday, Feb. 1 at 5 pm Code Review on milestone 1: –Coming soon; due Monday, Feb. 8 WD1: graphics proposal.

Slides:



Advertisements
Similar presentations
CS 11 C track: lecture 7 Last week: structs, typedef, linked lists This week: hash tables more on the C preprocessor extern const.
Advertisements

Agile Development & Companies
R4 Dynamically loading processes. Overview R4 is closely related to R3, much of what you have written for R3 applies to R4 In R3, we executed procedures.
Chapter 1: Computer Systems
Coding and Debugging. Requirements and Specification Recall the four steps of problem solving: Orient, Plan, Execute, Test Before you start the implementation.
Programming Types of Testing.
Hastings Purify: Fast Detection of Memory Leaks and Access Errors.
Debugging: Catching Bugs ( I ) Ying Wu Electrical & Computer Engineering Northwestern University ECE230 Lectures Series.
Debugging Introduction to Computing Science and Programming I.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Debugging CPSC 315 – Programming Studio Fall 2008.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Tirgul 8 Universal Hashing Remarks on Programming Exercise 1 Solution to question 2 in theoretical homework 2.
CODING Research Data Management. Research Data Management Coding When writing software or analytical code it is important that others and your future.
Administrative Stuff ECE 297. Administration Milestone 0: –Submit by Friday at 5 pm –Demo in lab this week –Write your name on the board when ready to.
Week 9 Part 2 Kyle Dewey. Overview Announcement More with structs and memory Assertions Exam #2 Course review.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
C++ / G4MICE Course Session 3 Introduction to Classes Pointers and References Makefiles Standard Template Library.
Chocolate Bar! luqili. Milestone 3 Speed 11% of final mark 7%: path quality and speed –Some cleverness required for full marks –Implement some A* techniques.
Designing For Testability. Incorporate design features that facilitate testing Include features to: –Support test automation at all levels (unit, integration,
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
COMP 208/214/215/216 Lecture 3 Planning. Planning is the key to a successful project It is doubly important when multiple people are involved Plans are.
A1 Visual C++.NET Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Quick Introduction The following.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Introduction to C++ // Program description #include directives int main() { constant declarations variable declarations executable statements return.
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Problem of the Day  Why are manhole covers round?
C Hints and Tips The preprocessor and other fun toys.
Application Profiling Using gprof. What is profiling? Allows you to learn:  where your program is spending its time  what functions called what other.
CSE 303 Concepts and Tools for Software Development Richard C. Davis UW CSE – 12/6/2006 Lecture 24 – Profilers.
Software Testing and Maintenance 1 Code Review  Introduction  How to Conduct Code Review  Practical Tips  Tool Support  Summary.
Moving Arrays -- 1 Completion of ideas needed for a general and complete program Final concepts needed for Final Review for Final – Loop efficiency.
Blackfin Array Handling Part 1 Making an array of Zeros void MakeZeroASM(int foo[ ], int N);
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
This document gives one example of how one might be able to “fix” a meteorological file, if one finds that there may be problems with the file. There are.
Administration Upcoming deadlines –Milestone 1 code due Monday Feb. 2 –Graphics proposal document: due Friday, Feb. 13 –Milestone 2 on web: due Monday,
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
1 Debugging and Syntax Errors in C++. 2 Debugging – a process of finding and fixing bugs (errors or mistakes) in a computer program.
Design - programming Cmpe 450 Fall Dynamic Analysis Software quality Design carefully from the start Simple and clean Fewer errors Finding errors.
C++ crash course Class 9 flight times program, using gdb.
Templates “Generic Programming” ECE Templates A way to write code once that works for many different types of variables –float, int, char, string,
Graphs, Continued ECE 297.
C++ / G4MICE Course Session 1 - Introduction Edit text files in a UNIX environment. Use the g++ compiler to compile a single C++ file. Understand the C++
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 2 – August 23, 2001.
CSC 213 – Large Scale Programming. Today’s Goal  Understand why testing code is important  Result of poor or no testing & embarrassment caused  Learn.
Version Control and SVN ECE 297. Why Do We Need Version Control?
A first attempt at learning about optimizing the TigerSHARC code TigerSHARC assembly syntax.
Using Sequential Containers Lecture 8 Hartmut Kaiser
ECE297 TA GUIDE Project supervision. Agenda M0 feedback Project overview M1 overview Project supervision.
Brief Version of Starting Out with C++ Chapter 1 Introduction to Computers and Programming.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
Implementation Topics Describe –Characteristics of good implementations –Best practices to achieve them Understand role of comments Learn debugging techniques.
“Generic Programming” ECE 297
Winter 2009 Tutorial #6 Arrays Part 2, Structures, Debugger
Measuring Where CPU Time Goes
Common C Programming Errors, GDB Debugging
CSCE 315 – Programming Studio, Fall 2017 Tanzir Ahmed
CSE 303 Concepts and Tools for Software Development
Testing (Continued).
Min Heap Update E.g. remove smallest item 1. Pop off top (smallest) 3
Review of Previous Lesson
SPL – PS1 Introduction to C++.
Chapter 9: Implementation
Presentation transcript:

Administration: Upcoming Due Dates Milestone 1: due Monday, Feb. 1 at 5 pm Code Review on milestone 1: –Coming soon; due Monday, Feb. 8 WD1: graphics proposal –Handout & rubric on website –Due Friday, Feb. 12 at 5 pm Milestone 2: Map visualization –Plan to release today –Due Monday, Feb. 22 at 5 pm

Good Code Style (Continued)

Thoughts on This Code? int checkWeights (int weights[20]) { for (int i = 0; i < 20; i++) { if (weights[i] < 0) return (-1); if (weights[i] == 0) return (0); } return (1); } 1.Using a “magic number”: 20 –Change array size: must find and change all 20’s 2.Returning magic numbers: -1, 0, 1 –Must read code carefully to see what each means

4. Use Named Constants const int NUM_WEIGHTS = 20; // 1. Constant variable #define WEIGHT_ZERO 0 // 2. Pre-processor constant enum WtReturn {HAS_NEG = -1, HAS_ZERO = 0, ALL_POS = 1}; // 3. make an “enumeration” (list) of int constants int checkWeights (int weights[NUM_WEIGHTS]) { for (int i = 0; i < NUM_WEIGHTS; i++) { if (weights[i] < 0) return (HAS_NEG); if (weights[i] == 0) return (HAS_ZERO); } return (ALL_POS); } Three ways to make constants  use any way you like Name: ALL CAPITALS (convention)

5. Many Short Functions Short functions –Easier to re-use –Fix bugs in one place, not many –Make code easier to read: more abstraction –How long should functions be? Should have many 5 to 10 line functions Should very rarely have a function > 100 lines

Thoughts on This Code? #include void myFunc (float a[], float b[], int nvals) { float absAvg1 = 0; for (int i = 0; i < nvals; i++) absAvg1 += abs(a[i]); absAvg1 /= nvals; float absAvg2 = 0; for (int i = 0; i < nvals; i++) absAvg2 += abs(b[i]); absAvg2 /= nvals;... } There is no honour in copy and paste coding! Refactor!

Better Version? #include float compAbsAvg (float array[], int nvals) { float absAvg = 0; for (int i = 0; i < nvals; i++) absAvg += abs (array[i]); return (absAvg / nvals); } void myFunc (float a[], float b[], int nvals) { float absAvg1 = compAbsAvg (a, nvals); float absAvg2 = compAbsAvg (b, nvals);... } 1. Not much shorter, but easier to read 2. Less chance of more code copying  future code will be shorter

6. Don’t Do Too Much in a Statement / Line #include #include “StreetsDatabaseAPI.h” string name = getIntersectionName(getStreetSegmentInfo( getIntersectionStreetSegment(startInter,0)).to); // Hard to read! unsigned firstSeg = getIntersectionStreetSegment (startInter,0); unsigned destInterId = getStreetSegmentInfo(firstSeg).to; string destInterName = getIntersectionName (destInterId); // Show your work  divide into several steps on several lines // Use good variable names to show what intermediate results // are.

7. Defensive Coding A.Use assertions to verify assumptions in your code void myFunc (int *ptr) { // Don’t ever call myFunc with a NULL ptr! if (*ptr == 1) { … #include void myFunc (int *ptr) { assert (ptr != NULL); if (*ptr == 1) { … Exits program if ptr is NULL (condition not true) Better than a comment: –Checked at runtime & gives useful error message > assert failed on line 208 of file myFunc.cpp: ptr != NULL

What If I Need That Last Bit of Speed? #define NDEBUG // Just turned off assertion checking // Make sure this line is in front of // #include #include void myFunc (int *ptr) { ptr = NULL; assert (ptr != NULL); // Not checked  won’t fire. … Can turn off assertion checking in release build –Avoids any speed overhead –Leave on for debug build for extra checking –And maybe leave on in release too if your program not very time critical

7. Defensive Coding B. Set deleted / invalid pointers to NULL delete (ptr); ptr = NULL; // Now we’ll crash if we try to use it  good! … ptr->value = 1; // Will seg fault immediately C. Self-checking code (advanced technique) program_ok = validate_key_data_structure (my_struct);

12 Should have used assert or validity checkers!

Find the Bug! const int NUM_WEIGHTS = 20; // 1. Constant variable #define WEIGHT_ZERO 0 // 2. Pre-processor constant enum WtReturn {HAS_NEG = -1, HAS_ZERO = 0, ALL_POS = 1}; // 3. make an “enumeration” (list) of int constants int checkWeights (int weights[NUM_WEIGHTS]) { for (int i = 0; i < NUM_WEIGHTS; i++) { if (weights[i] = 0) return (HAS_ZERO); if (weights[i] < 0) return (HAS_NEG); } return (ALL_POS); } weights = {-1, 2, 3, 4, 5, 6, … 20} checkWeights returns ALL_POS Test program, find a failing case …

8. Use Compiler Warnings > g++ -Wall weights.cpp > weights.cpp: In function ‘int checkWeights(int*)’: > weights.cpp:11: warning: suggest parentheses around assignment used as truth value int checkWeights (int weights[NUM_WEIGHTS]) { for (int i = 0; i < NUM_WEIGHTS; i++) { if (weights[i] = 0) return (HAS_ZERO); if (weights[i] < 0) return (HAS_NEG); } return (ALL_POS); } Line 11

8. No Warnings Don’t have any warnings in your code –Warnings flag potentially problematic code –If you leave some warnings in, hard to see new ones –Fix right away: stay at 0 warnings! –Tell compiler to generate all useful warnings (more than default) Command line: g++ –Wall Netbeans: –File | Project Properties | C++ Compiler | More Warnings We have turned on warnings in your makefile

One Code Base to Rule Them All Code will be read more than written –By you –By others –Make it readable! Code will be modified many times –Make small functions & avoid repeated code Keep the tests with the code –Automated, so you can re-run often Keep documentation in the code -- comments!

Code Reviews If you do one thing for code quality  code reviews Altera: periodic review –4 reviewers read code written by one team member –Significant amount: ~400 – 1000 lines –Write down thoughts –Then meet to discuss  readable, clear, efficient? Google: every commit reviewed and approved –Integrated into source code control system –Change not visible to others until reviewed & approved

Code Reviews This course: you will read another team’s milestone1 code submission –Both teams have the same TA Write a short (1 page) code review –Can have an appendix with code examples –2% of your final mark –Does not affect the other team’s grade TA already reviewed their code for style Same TA will read your code review Code sent to you early in week of Feb. 1 Review due Monday, Feb. 8

Profiling Code Measuring Where CPU Time Goes

My Code Is Too Slow – Why? Look at code  what O() is it? –Loading: O(N) unavoidable and OK O(N 2 )  not good if N can get big –Look-ups If you’ll do something N times, try to keep it O(1) or O(log N)

My Code is Complex! Can’t figure out O() Or O() looks OK, but still not fast enough Profile! –Measure where the time goes

Simple Profiling: Manual Random Sampling 1.Run the debugger 2.Stop it with Debug  Pause 3.Look at the subroutine and line where you paused 4.Examine the call stack to see how you got there 5.Continue execution with Debug  Continue More CPU time in a routine  higher probability of stopping there Repeat several times and find you’re in the same routine  you’ve found the problem

Detailed Profiling: gprof Tool gprof tool –Randomly samples the function your program is in ~ every 1 ms –Also records how it got there (call stack / call graph) –Then summarizes the output for you How is this random sampling done? –Program asks to be interrupted ~1000x / second by operating system –Each interrupt  record function you are in

gprof Tool: How to Use 1.Compile your program with the right options –Add –pg option to compiler  instruments exe –Optimization? –Yes: want to speed up release build: -O3 –No: harder to interpret results (inlined functions) make CONF=debug_profile or make CONF = release_profile

gprof Tool: How to Use 2.Run program normally –myProg.exe arg1 … –Collects statistics, stores in big file (gmon.out) –Program runs only a little slower (~30%) 3.Run gprof to summarize / interpret output –gprof myProg.exe > outfile.txt –Reads gmon.out, generates readable outfile.txt –Even better: can visualize (graphics) gprof myProg.exe gmon.out | gprof2dot. py -s | xdot - ECE 297 Profiling Quick Start Guide

Example: Extract Negatives #include using namespace std; vector extract_negatives (vector & numbers) { vector negatives; int i = 0; while(i < numbers.size()) { if(numbers[i] < 0) { negatives.push_back(numbers[i]); numbers.erase(numbers.begin() + i); } else { i++; //Next element } return negatives; } Takes 30 s when given an 800,000 element vector. Too slow  why?

Visualized Call Graph Extract negatives called once by main Takes 71% of time Erase called over 640,000 times Takes 53% of time  biggest problem push_back() Estimated 37% of time This is an over-estimate: sample-based profiling isn’t perfect