Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 10: How to Write Efficient Programs in Matlab Please change directory to directory E:\Matlab (cd E:\Matlab;) From the course website ( ) Download: matlab_t10.zip OR t10.m, sumConsecutiveKNums.m, sumConsecutiveKNumsFixed.m, writingEfficientCodeExamples.m, computeSinSlowAndFast.m, computeSinFast.m, computeSinSlow.m, twinPeaksExample.m, computeTwinPeaksFunc.m,, computeTwinPeaksFuncForSinglePoint.m, findPsychoScore.m
2 Goals M-lint Just-In-Time accelerator Profiler Example of efficient vs. non- efficient algorithm: Binary search Resource:
3 Before We Start Correct code is always more important than speed Keep your code readable Optimize the bottlenecks
4 M-lint Check Code Report edit sumConsecutiveKNums.m Tools -> M lint -> Show M lint report %#ok – ignore this line Advanced: Preference -> M-lint The M-Lint Code Check Report displays potential errors and problems, as well as opportunities for improvement in your code
5 M-lint Check Code Report – Lets Fix the Example Fix: sumConsecutiveKNums.m Tools -> M lint -> Show M lint report Save it as sumConsecutiveKNumsFixed.m Compare the files using: Tools -> Compare against -> Browse
6 Comparing Files – Compare the Fixed File to the Original sumConsecutiveKNums.msumConsecutiveKNumsFixed.m
7 More about M-lint
Weizmann 2010 © 8 Accelerating Your Code Resources: echdoc/matlab_prog/ch7_pe10.html echdoc/matlab_prog/ch7_pe10.html -up-matlab-applications/
9 Write Efficient Code by Using Efficient Algorithms and Efficient Implementation Efficient algorithm Examples: Binary search Bubble sort Efficient implementation Examples: Using vectors manipulation instead of loops Allocating memory in advance Matlab tries to accelerate the code running speed…
10 Matlab Goal is to Convert the M-code Into the Most Efficient Computer Language Code Goal: Best computer language code Computer language Intermediate language x = linspace(0,2*pi,1000); y = sin(x); x = linspace(0,2*pi,1000); z = zeros(size(x)); for i=1:length(x) z(i) = sin(x(i)); end ==
11 Matlab Just-In-Time Accelerator Improving the speed of M-code functions and scripts, particularly self-contained loops.
12 Matlab Just-In-Time Accelerator Matlab 6.5 and later versions Not supported (not accelerated): Cell, Structure, sparse matrix Arrays of more than three dimensions Changing the data type or the shape of an array Calling non built-in functions (M-files) if, elseif, while, and switch – if the logical expression does not evaluate to a scalar Matlab can represent sparse matrices. Checkout sparse doc
13 Timing a Run We can time a run by planting in the code, function that measure the run time: tic, toc cputime Examples: CPU time – The amount of time a computer program uses in processing on a CPU prev_cpu_time = cputime; a = rand(1,100000); cur_cpu_time = cputime; cpu_run_time = … cur_cpu_time-prev_cpu_time run_time = Elapsed time is seconds. tic; a = rand(1,100000); toc; Recommended
14 Matlab Profiler Helps us to Focus on the Code Bottlenecks Profiling - is a way to measure where the program spends its time Profiling helps to uncover performance problems that you can solve by: Avoiding unnecessary computation. Changing your algorithm to avoid costly functions Avoiding recomputation by storing results for future use
15 Matlab Can Produce a Graphical Profiling Report profile('on'); profile('viewer'); profsave(profile('info'),… 'example_profile'); Turning the profiler on Turning the profiler off and presenting the results Saving the profiler results in HTML format
16 Profiler Example - 1 edit writingEfficientCodeExamples.m; Lets run the first example: profile('on'); vec1 = linspace(0,2*pi,10^4); [vec1_sin_fast vec1_sin_slow] = computeSinSlowAndFast(vec1); profile('viewer'); profsave(profile('info'),'example1_profile');
17 Profiler Example 1 – Profile Summary Dark band – self time
18 Profiler Example 1 – Focusing on a Function
19 Function listing highlights time consumintg lines
20 The Profiler Gives Also the M-lint Analysis
21 Profiler Example - 2 Try run the second example: In function computeTwinPeaksFunc: Try to change to computation of Z to a function: How does it affect the code? Why? Try saving the profiler results in HTML format using: profile('on'); twinPeaksExample(); profile('viewer'); %Z(i,j) = X(i,j) * exp(X(i,j)^2-Y(i,j)^2); Z(i,j) = computeTwinPeaksFuncForSinglePoint(X(i,j),Y(i,j)); profsave(profile('info'),'example2_profile');
Weizmann 2010 © 22 Efficient vs. Non- Efficient Algorithm Binary search (Lecture Reminder)
23 Divide and Conquer Paradigm Since the lion is dangerous we can’t catch him, so we start building fences until we close him in a cage… First Strategy: How do you catch a lion in the desert?
24 Divide and Conquer Paradigm Divide and conquer strategy (“lion in the desert”): How do you catch a lion in the desert?
25 Implementation of binary search We have data sets of last psychometric exam results We want to write a function that: Given an ID, finds its corresponding score as fast as possible IDscore …… Sorted
26 We Will Use the “Lion in the Desert” Strategy – Binary Search Example: Find id = compare IDs = left index / right index = Requested ID
27 Binary Search – IDs example function [id_index] = local_findIdIndexBinary(ids, id) %init id_index = NaN; l_ind = 1; r_ind = length(ids); mid_ind = floor((l_ind + r_ind) / 2);
28 Binary Search – IDs example function [id_index] = local_findIdIndexBinary(ids, id) while l_ind < r_ind cur_mid_id = ids(mid_ind); if id == cur_mid_id id_index = mid_ind; return; elseif id < cur_mid_id r_ind = mid_ind; mid_ind = floor((l_ind + r_ind) / 2); else %id > cur_mid_id l_ind = mid_ind; mid_ind = ceil((l_ind + r_ind) / 2); end l_indr_indmid_ind
29 Performance Comparison of Linear Search and Binary Search Check out t10.m and findPsychoScore.m Results for three search of random id: test: Linear search took comparisons Linear search find that the score of ID is:440 Binary search took 17 comparisons Binary search find that the score of ID is: test: Linear search took 2702 comparisons Linear search find that the score of ID is:571 Binary search took 17 comparisons Binary search find that the score of ID is: test: Linear search took comparisons Linear search find that the score of ID is:720 Binary search took 17 comparisons Binary search find that the score of ID is:720 Comment: Worst case Average case
30 Summary M-lint Just-In-Time accelerator Profiler Example of efficient vs. non- efficient algorithm: Binary search