Reduce runtime of my code

조회 수: 4 (최근 30일)
Clodoaldo de Souza Faria Júnior
답변: Walter Roberson 2022년 3월 23일
In my code I need to find the time in seconds in the table called "data", being that the seconds time are storage in the first column.
I need to do it a lot of times in my code and this operation take a lot of time to run.
How I can reduce this runtime?
aux = fix(totalSeconds/60)*60;
ltime = find(data(:,1)== aux);
dataTime = data(ltime,:);

채택된 답변

Walter Roberson
Walter Roberson 2022년 3월 23일
Assuming that it is the same data variable that is being searched each time:
Look at fix(totalSeconds/60)*60 . The result has to be an exact integer multiple of 60. Any entry in data in which the first column is not an exact integer multiple of 60 cannot be matched by this code. So if we are searching the same data repeatedly, then we could save time by doing
temp = data(:,1)/60;
mask = temp == floor(temp); %was it an exact multiple of 60?
data60 = data(mask, :);
and then inside the loop only search data60 instead of the larger data .
So now data60 contains only exact multiples of 60 in the first column. Examine fix(totalSeconds/60)*60 again. Do we need the *60 there? Or could we store data(:,1)/60 instead, knowing that that will be an integer?
We can also reduce the find() to a logical mask:
temp = data(:,1)/60;
mask = temp == floor(temp); %was it an exact multiple of 60?
data60 = [temp(mask), data(mask,2:end)];
and then in the loop,
aux = fix(totalSeconds/60);
ltime = data60(:,1) == aux;
dataTime = data60(ltime,:);
Summary:
  • we now ignore the entries in data that cannot possibly mask because they are not exact multiples of 60
  • we pre-divide the times by 60 to get integer minutes
  • we skip multiplying the minutes by 60
  • we use logical indexing instead of find()
Most of this is not useful if it turns out that data is changing each iteration... if so then you should let us know what (if anything) is the same for each iteration.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with Optimization Toolbox에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by