Reduce runtime of my code

3 ビュー (過去 30 日間)
Clodoaldo de Souza Faria Júnior
Clodoaldo de Souza Faria Júnior 2022 年 3 月 23 日
回答済み: 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 Center および File ExchangeProgramming についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by