find(condition,1) is slower than using a loop--any way to speed up?

1 visualización (últimos 30 días)
Marshall
Marshall el 5 de Oct. de 2018
Editada: Jan el 9 de Oct. de 2018
In general, using a logical condition in conjunction with find is slower than using a tight loop:
loc = find(X>a, 1)
is slower than using a for loop:
for i = 1:N
if(X(i)>a)
loc = i;
break;
end
end
The reason for this is because the logical operator X>a operates on all elements of the vector X, which is wasteful. Surely the JIT is smart enough to optimize
find(condition,1)
such that condition is applied and tested until the value is found. Do any shortcuts for this optimization exist?
  33 comentarios
Bruno Luong
Bruno Luong el 9 de Oct. de 2018
Editada: Bruno Luong el 9 de Oct. de 2018
function calls: that implies some small mxArray header copying, etc... we talking about sub µs by calling here.
Jan
Jan el 9 de Oct. de 2018
Editada: Jan el 9 de Oct. de 2018
@Bruno: In the worst case, all X and compared in the Mex function and in find(X>a, 1). That the latter is faster might be caused by MMX/SSE code, which checks 8 or 16 logicals at once. SSE could be used for the comparison also, but the code will be much larger and has to catch the exceptions that the mxArray does not start or end at a multiple of the cache-line size. If we take into account the runtime and teh programming+debug time of the code, your simple C-Mex function is likely to be optimal. Please post is as an answer, because it solves the problem.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by