Download presentation
Presentation is loading. Please wait.
Published byEmory O’Connor’ Modified over 9 years ago
1
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
2
Good Code Style (Continued)
3
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
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
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
6
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!
7
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
8
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.
9
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
10
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
11
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
12 Should have used assert or validity checkers!
13
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 …
14
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
15
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
16
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!
17
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
18
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
19
Profiling Code Measuring Where CPU Time Goes
20
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)
21
My Code is Complex! Can’t figure out O() Or O() looks OK, but still not fast enough Profile! –Measure where the time goes
22
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
23
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
24
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
25
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
26
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?
27
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.