Presentation is loading. Please wait.

Presentation is loading. Please wait.

Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 10: How to Write Efficient Programs in Matlab Please change directory to directory E:\Matlab.

Similar presentations


Presentation on theme: "Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 10: How to Write Efficient Programs in Matlab Please change directory to directory E:\Matlab."— Presentation transcript:

1 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 (http://www.weizmann.ac.il/midrasha/courses/MatlabIntro//course_outline.htm )http://www.weizmann.ac.il/midrasha/courses/MatlabIntro//course_outline.htm 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 2 Goals M-lint Just-In-Time accelerator Profiler Example of efficient vs. non- efficient algorithm: Binary search http://www.mathworks.com/matlabcentral/files/5685/matopt.pdf Resource:

3 3 Before We Start Correct code is always more important than speed Keep your code readable Optimize the bottlenecks

4 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 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 6 Comparing Files – Compare the Fixed File to the Original sumConsecutiveKNums.msumConsecutiveKNumsFixed.m

7 7 More about M-lint

8 Weizmann 2010 © 8 Accelerating Your Code Resources: http://www.mathworks.com/access/helpdesk_r13/help/t echdoc/matlab_prog/ch7_pe10.html http://www.mathworks.com/access/helpdesk_r13/help/t echdoc/matlab_prog/ch7_pe10.html http://blogs.mathworks.com/loren/2008/06/25/speeding -up-matlab-applications/

9 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 10 Matlab Goal is to Convert the M-code Into the Most Efficient Computer Language Code Goal: Best computer language code Computer language 0100110101 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 11 Matlab Just-In-Time Accelerator Improving the speed of M-code functions and scripts, particularly self-contained loops.

12 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 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 = 0.0156 Elapsed time is 0.009608 seconds. tic; a = rand(1,100000); toc; Recommended

14 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 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 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 17 Profiler Example 1 – Profile Summary Dark band – self time

18 18 Profiler Example 1 – Focusing on a Function

19 19 Function listing highlights time consumintg lines

20 20 The Profiler Gives Also the M-lint Analysis

21 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');

22 Weizmann 2010 © 22 Efficient vs. Non- Efficient Algorithm Binary search (Lecture Reminder)

23 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 24 Divide and Conquer Paradigm Divide and conquer strategy (“lion in the desert”): How do you catch a lion in the desert?

25 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 1920345720 1920352670 1930114700 …… Sorted

26 26 We Will Use the “Lion in the Desert” Strategy – Binary Search Example: Find id 415 101115200304415516550602711808901903980 = compare IDs = left index / right index = Requested ID

27 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 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 29 Performance Comparison of Linear Search and Binary Search Check out t10.m and findPsychoScore.m Results for three search of random id: ------------------ test:1 --------------------------- Linear search took 83231 comparisons Linear search find that the score of ID 83229533 is:440 Binary search took 17 comparisons Binary search find that the score of ID 83229533 is:440 ------------------ test:2 --------------------------- Linear search took 2702 comparisons Linear search find that the score of ID 2627259 is:571 Binary search took 17 comparisons Binary search find that the score of ID 2627259 is:571 ------------------ test:3 --------------------------- Linear search took 23594 comparisons Linear search find that the score of ID 23657664 is:720 Binary search took 17 comparisons Binary search find that the score of ID 23657664 is:720 Comment: Worst case Average case

30 30 Summary M-lint Just-In-Time accelerator Profiler Example of efficient vs. non- efficient algorithm: Binary search


Download ppt "Weizmann 2010 © 1 Introduction to Matlab & Data Analysis Tutorial 10: How to Write Efficient Programs in Matlab Please change directory to directory E:\Matlab."

Similar presentations


Ads by Google