Tutorial_10

advertisement
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 )
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
Weizmann 2010 ©
1
Goals




M-lint
Just-In-Time accelerator
Profiler
Example of efficient vs. non- efficient
algorithm: Binary search
Resource:
http://www.mathworks.com/matlabcentral/files/5685/matopt.pdf
2
Before We Start
Correct code is always more
important than speed


Keep your code
readable
Optimize the
bottlenecks
3
M-lint Check Code Report
The M-Lint Code Check
Report displays potential
errors and problems,
as well as opportunities for
improvement in your code

edit sumConsecutiveKNums.m

Tools -> M lint
-> Show M lint report
%#ok – ignore this line

Advanced: Preference -> M-lint

4
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
5
Comparing Files – Compare
the Fixed File to the Original
sumConsecutiveKNums.m
sumConsecutiveKNumsFixed.m
6
More about M-lint
7
Accelerating Your Code
Resources:
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/
Weizmann 2010 ©
8
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… 9
Matlab Goal is to Convert the M-code Into
the Most Efficient Computer Language Code
Intermediate
language
Computer
language
0100110101
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
Goal:
Best computer
language code
10
Matlab Just-In-Time Accelerator
Improving the speed of M-code
functions and scripts, particularly
self-contained loops.
11
Matlab Just-In-Time Accelerator


Matlab 6.5 and later versions
Not supported (not accelerated):





Matlab can represent
sparse matrices .
Checkout sparse doc
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
12
Timing a Run

We can time a run by planting in the
code, function that measure the run time:



tic, toc
cputime
CPU time – The amount of time a computer
program uses in processing on a CPU
Examples:
Recommended
tic;
a = rand(1,100000);
toc;
Elapsed time is 0.009608 seconds.
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
13
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
14
Matlab Can Produce a
Graphical Profiling Report
profile('on');
Turning the profiler on
<tested code>
Turning the profiler off
profile('viewer'); and presenting the results
profsave(profile('info'),…
'example_profile');
Saving the profiler results in HTML format
15
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');
16
Profiler Example 1 –
Profile Summary
Dark band –
self time
17
Profiler Example 1 –
Focusing on a Function
18
Function listing highlights
time consumintg lines
19
The Profiler Gives Also the
M-lint Analysis
20
Profiler Example - 2

Try run the second example:
profile('on');
twinPeaksExample();
profile('viewer');

In function computeTwinPeaksFunc:

Try to change to computation of Z to a function:
%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));


How does it affect the code? Why?
Try saving the profiler results in HTML
format using:
profsave(profile('info'),'example2_profile');
21
Efficient vs. Non- Efficient Algorithm
Binary search (Lecture Reminder)
Weizmann 2010 ©
22
Divide and Conquer Paradigm
How do you catch a lion in the desert?
Since the lion is dangerous we can’t catch him, so we
start building fences until we close him in a cage…
First Strategy:
23
Divide and Conquer Paradigm
How do you catch a lion in the desert?
Divide and conquer strategy (“lion in the desert”):
24
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
Sorted
ID
score
1920345 720
1920352 670
1930114 700
…
…
25
We Will Use the “Lion in the
Desert” Strategy – Binary Search

Example: Find id 415
= left index /
right index
= Requested ID
= compare IDs
101
115
200
304
415
516
550
602
711
808
901
903
980
26
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>
27
Binary Search – IDs example
function [id_index] = local_findIdIndexBinary(ids, id)
<init>
l_ind
mid_ind
r_ind
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
end
28
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
29
Summary




M-lint
Just-In-Time accelerator
Profiler
Example of efficient vs. non- efficient
algorithm: Binary search
30
Download