Reduce runtime of my code

3 次查看(过去 30 天)
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