benchmarking anonymous functions with timeit
Mostrar comentarios más antiguos
I was reading this Measure the Performance of Your Code and was wondering about a more complicated example using timeit with nested anonymous functions?
Suppose that you want to compare the speed of different ways to flatten a matrix into a vector.
% make an image
widthPixels = 640;
heightPixels = 480;
raw_data = @(width,height)(randn(width,height));
nrmi = @(x)(x/(max(x(:))));
image = @(counts)(single( uint8(255*counts)).^0.5);
% different ways to flatten
alg1 = @(x)(x(:));
alg2 = @(x)(reshape(x,1,[]));
alg3 = @(x)(reshape(x,[],1)'));
% basic way
nIterations = 100;
totalTime = 0;
for i = 1:nIterations
tic;
y = alg1(x);
totalTime = totalTime + toc;
end
avgTime = totalTime / nIterations;
But I really want to use timeit but not quite sure how it works. Here's the basic idea of what I'd want to do.
timeit(alg1(image(raw_data(heightPixels,widthPixels)))
Or just define multiple anonymous functions on one line. Maybe something like this? I'm not sure how you would chain all of them together...
image = @()(single( uint8(255*@(x)(x/(max(x(:)))).^0.5);
4 comentarios
"I'm not sure how you would chain all of them together..."
An anonymous function is just a function, so when you want to use it you can call it just like any other function.
"Or just define multiple anonymous functions on one line. Maybe something like this?"
Given that you have already defined a function named NRMI which does exactly that calculation, try simply calling NRMI, rather than trying to redefine the same anonymous function again inside some other code.
A = imread('ngc6543a.jpg');
alg1 = @(x)(x(:));
alg2 = @(x)(reshape(x,1,[]));
alg3 = @(x)(reshape(x,[],1).');
timeit(@() alg1(A))
timeit(@() alg2(A))
timeit(@() alg3(A))
seth patterson
el 25 de Nov. de 2022
"And you wanted the timeit function to call the pipeline of functions?"
As I wrote in my last comment, you need to call them, unlike your attempts to create function handles out of things that are already function handles:
thisisafunctionhandle = @(x) dowhateverwith(x); % this defines a function handle.
@thisisafunctionhandle % <- ERROR! What you are doing, trying to create a function handle out of a function handle
thisisafunctionhandle(invalue) % <- What you should be doing, calling the function!
You should revise how function handles are created and called:
w = 3;
h = 4;
timeit(@() alg1(image(nrmi(raw_data(w,h)))))
@seth patterson: Just a note: sqrt is faster than .^0.5 :
x = rand(640, 480);
timeit(@() sqrt(x))
timeit(@() x.^0.5)
Respuestas (0)
Categorías
Más información sobre Performance and Memory en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!