Accelerating access of struct members

9 Ansichten (letzte 30 Tage)
Torsten Knüppel
Torsten Knüppel am 2 Mär. 2018
Kommentiert: Torsten Knüppel am 12 Mär. 2018
Dear all,
I noticed that accessing data within a struct seems to be very slow compared to an array. To illustrate this, I put together a small script that randomly accesses data within an array and a struct respectively:
M = 20;
N = 1e8;
data = rand(M, 1);
data_struct = struct('a', num2cell(data));
for n = 1:N
i = round(M * rand() + 1 / 2);
c = data_struct(i).a;
e = data(i);
end
Profiling this script reveals that the assignment of c consumes about 20x the time of assigning e. Is there any way to accelerate the access of the struct, i.e. by somehow specifying the type of data it contains?

Akzeptierte Antwort

Sujit Muduli
Sujit Muduli am 9 Mär. 2018
Bearbeitet: Sujit Muduli am 9 Mär. 2018
Hi Torsten,
Profiling might not give you the exact result but you may use tic-toc to measure the exact time taken. Please note, using structure arrays is about 2 times slower than the simple matrix in MATLAB. I also did a small experiment to profile the time taken in the assignments in my MATLAB R2017a. Profiler usually gives you relative time values, not the exact this helps you find the bottleneck in your program. In this case, it is doing its job well by hinting the bottleneck is in the access of the struct values.
Thanks
Sujit
  1 Kommentar
Torsten Knüppel
Torsten Knüppel am 12 Mär. 2018
Thanks for the reply - it really helped interpreting the profiler's results.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Jan
Jan am 9 Mär. 2018
Matlab's JIT acceleration can improve te execution speed of e.g. loops massively. During debugging and profiling the JIT is disabled, because it can reorder the commands to increase the speed, but this would confuse the examination of the code. Therefore the power of the profiler is limited, unfortunately.
Of course accessing a field of a struct takes time, because there is a substantial work to do in each iteration. Storing data in structs help to write clear code, but it reduces the execution speed compared to arrays.
  1 Kommentar
Torsten Knüppel
Torsten Knüppel am 12 Mär. 2018
Good to know what causes the differences between the profiler's results and what tic-toc yields.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Structures 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!

Translated by