Page 1
Weizmann 2010 © 1
Introduction to Matlab & Data Analysis
Tutorial 10: How to Write Efficient Programs in
MatlabPlease change directory to directory E:\Matlab (cd E:\Matlab;)
From the course website
(http://www.weizmann.ac.il/midrasha/courses/MatlabIntro//course_outline.htm )
Download:matlab_t10.zip ORt10.m, sumConsecutiveKNums.m, sumConsecutiveKNumsFixed.m, writingEfficientCodeExamples.m , computeSinSlowAndFast.m,computeSinFast.m, computeSinSlow.m,twinPeaksExample.m, computeTwinPeaksFunc.m, ,computeTwinPeaksFuncForSinglePoint.m, findPsychoScore.m
Page 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.pdfResource:
Page 3
3
Before We Start
Correct code is always more important than
speed
Keep your code readable
Optimize the bottlenecks
Page 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
Page 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
Page 6
6
Comparing Files – Compare the Fixed File to the Original
sumConsecutiveKNums.m
sumConsecutiveKNumsFixed.m
Page 7
7
More about M-lint
Page 8
Weizmann 2010 © 8
Accelerating Your Code
Resources: http://www.mathworks.com/access/helpdesk_r13/help/techdoc/matlab_prog/ch7_pe10.html
http://blogs.mathworks.com/loren/2008/06/25/speeding-up-matlab-applications/
Page 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…
Page 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
==
Page 11
11
Matlab Just-In-Time Accelerator
Improving the speed of M-code functions and scripts, particularly self-contained loops.
Page 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
Page 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_timerun_time = 0.0156Elapsed time is 0.009608
seconds.
tic;
a = rand(1,100000);
toc;
Recommended
Page 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
Page 15
15
Matlab Can Produce a Graphical Profiling Report
profile('on'); <tested code> profile('viewer'); profsave(profile('info'),…
'example_profile');
Turning the profiler on
Turning the profiler offand presenting the results
Saving the profiler results in HTML format
Page 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');
Page 17
17
Profiler Example 1 – Profile Summary
Dark band – self time
Page 18
18
Profiler Example 1 – Focusing on a Function
Page 19
19
Function listing highlights time consumintg lines
Page 20
20
The Profiler Gives Also the M-lint Analysis
Page 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');
Page 22
Weizmann 2010 © 22
Efficient vs. Non- Efficient Algorithm
Binary search (Lecture Reminder)
Page 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?
Page 24
24
Divide and Conquer Paradigm
Divide and conquer strategy (“lion in the desert”):
How do you catch a lion in the desert?
Page 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
ID score
1920345
720
1920352
670
1930114
700
… …
Sorted
Page 26
26
We Will Use the “Lion in the Desert” Strategy – Binary Search
Example: Find id 415
101 115 200 304 415 516 550 602 711 808 901 903 980
= compare IDs
= left index / right index
= Requested ID
Page 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);
<main loop>
Page 28
28
Binary Search – IDs example
function [id_index] = local_findIdIndexBinary(ids, id) <init>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); endend
l_ind r_indmid_ind
Page 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 comparisonsLinear search find that the score of ID 83229533 is:440Binary search took 17 comparisonsBinary search find that the score of ID 83229533 is:440------------------ test:2 ---------------------------Linear search took 2702 comparisonsLinear search find that the score of ID 2627259 is:571Binary search took 17 comparisonsBinary search find that the score of ID 2627259 is:571------------------ test:3 ---------------------------Linear search took 23594 comparisonsLinear search find that the score of ID 23657664 is:720Binary search took 17 comparisonsBinary search find that the score of ID 23657664 is:720
Comment:Worst caseAverage case
Page 30
30
Summary
M-lint Just-In-Time accelerator Profiler Example of efficient vs. non- efficient
algorithm: Binary search