필터 지우기
필터 지우기

why arrayfun does NOT improve my struct array operation performance

조회 수: 3 (최근 30일)
HaveF
HaveF 2012년 6월 23일
here is the input data:
% @param Landmarks:
% Landmarks should be 1*m struct.
% m is the number of training set.
% Landmark(i).data is a n*2 matrix
old function:
function Landmarks=CenterOfGravity(Landmarks)
% align center of gravity
for i=1 : length(Landmarks)
Landmarks(i).data=Landmarks(i).data - ones(size(Landmarks(i).data,1),1)...
*mean(Landmarks(i).data);
end
end
new function which use arrayfun:
function [Landmarks] = center_to_gravity(Landmarks)
Landmarks = arrayfun(@(struct_data)...
struct('data', struct_data.data - repmat(mean(struct_data.data), [size(struct_data.data, 1), 1]))...
,Landmarks);
end %function center_to_gravity
when using profiler, I find the usage of time is NOT what I expected:
Function Total Time Self Time*
CenterOfGravity 0.011s 0.004 s
center_to_gravity 0.029s 0.001 s
Can someone tell me why?

채택된 답변

Jan
Jan 2012년 6월 23일
ARRAYFUN is not more efficient than a FOR loop, because it has a FOR loop internally.
Another idea:
for i = 1 : length(Landmarks)
data = Landmarks(i).data;
Landmarks(i).data= bsxfun(@minus, data, sum(data, 1) / size(data, 1));
end
Reduce the repeated access to a field, SUM/LENGTH is faster than MEAN, BSXFUN avoid the creation of a temporary array.
Or:
for i = 1 : length(Landmarks)
data = Landmarks(i).data;
m = sum(data, 1) / size(data, 1);
data(:, 1) = data(:, 1) - m(1);
data(:, 2) = data(:, 2) - m(2);
Landmarks(i).data = data;
end
  댓글 수: 3
HaveF
HaveF 2012년 6월 24일
In terms of why, Pursuit's explanation seems reasonable.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2012년 6월 23일
Also, profile disables a number of optimizations, so you cannot use profiler to determine full execution rate. Try timeit
  댓글 수: 2
HaveF
HaveF 2012년 6월 24일
Thanks for this great tip! I decide to use timeit when compare two methods, use profiler to determine the bottleneck of my program for its relative inaccuracy time.
HaveF
HaveF 2012년 6월 24일
BTW, when I use profiler, I have to set the number of active CPUs to one before my start profiling, should I do this before I use timeit?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Install Products에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by