- 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 (최근 30일)
이전 댓글 표시
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
채택된 답변
Suraj Kumar
2024년 9월 5일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!