- You can recompute ‘x’ outside the loop as it stays the same in each iteration .
- Pre-allocation of ‘R’ can be done outside the loop to increase performance.
I'm looking for a faster way to roll through a set of indexes into an array by using the bitand() function.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dr W Kurt
am 4 Sep. 2024
Beantwortet: Suraj Kumar
am 5 Sep. 2024
I saw something awhile back that was much faster and as I recall the method was to convert bitand(a,b) a and b to double, then a few multiplies, a floor operation and a divide.
Here's the slow code... first the Test Bench (TB.m), then the real-time task which must be fast:
%% Test Bench
%
clear all
close all
%
b = uint32(0);
figure
for jj = 1:100
for k = 1:4096
R(k) = RxTask();
end
x = 1:4096;
R = R.*1e6; % convert to microseconds
semilogy(x,R)
hold on
drawnow
end
%
grid on
grid minor
title('RxTask Timein usec''s')
function [R] = RxTask()
%
persistent c d e
if isempty(c)
c = uint32(zeros(1,4096));
d = uint32(0);
e = uint32(4095);
end
%
tic
d = d + uint32(1);
d = bitand(d,e);
st = toc;
% R.d = d;
R = st;
end
0 Kommentare
Akzeptierte Antwort
Suraj Kumar
am 5 Sep. 2024
From what I gather, you are trying to find a faster way to roll through a set of indices into an array by using the ‘bitand’ operation.
To optimize the ‘bitand’ operation, you can use the following mathematical operations to replicate the behaviour of the same :
Here is an improved version of the ‘RxTask’ function:
function [R] = RxTaskOptimized()
persistent c d e
if isempty(c)
c = uint32(zeros(1,4096));
d = uint32(0);
e = uint32(4095);
end
tic
d = mod(d + 1, e + 1);
st = toc;
R = st;
end
Now to further optimize your code, you can check the following steps as well:
b = uint32(0);
x = 1:4096; % Precompute x outside the loop
R = zeros(1, 4096); % Preallocate R outside the loop
figure
for jj = 1:100
for k = 1:4096
R(k) = RxTaskOptimized();
end
R = R .* 1e6; % convert to microseconds
semilogy(x, R)
hold on
drawnow
end
You can monitor the performance by using the MATLAB Profiler for both the methods:
Optimized function:
Original function:
Happy Coding!
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Introduction to Installation and Licensing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!