Pre-allocating a function since initialization is slow
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hi guys,
Consider this code:
clc; clear all;
t2=linspace(0,pi,10);
f2=cos(t2);
tic; cumtrapz(t2,f2); t1=toc
tic; cumtrapz(t2,f2); t2=toc
t1/t2
It turns out that the first call to cumtrapz takes around 7 times longer.
I want to run the cumtrapz function in real time within a function that is called by a nonlinear solver (IPOPT), many times +20000 in a single timestep. To be clear; the cumtrapz is only called ONCE every function call.
How can I make sure that everytime cumtrapz it is called, it does not take 7 times longer, due to initialisation stuff. In other words, can I e.g. preallocate the cumtrapz function in the workspace?
*Note that this has nothing to do with proallocating the output of cumtrapz since it is not stored to workspace in the code above.
0 comentarios
Respuestas (1)
Daniel Shub
el 27 de Mzo. de 2012
What you are seeing is the reason that people suggest that you do not use
clear all
As long as you do not clear the cumtrapz function from memory (or its subfunctions) it won't take 7x as long.
5 comentarios
Daniel Shub
el 27 de Mzo. de 2012
Timing things in MATLAB that take less than 100 microseconds tends not to be reliable. If I increase linspace from 10 points to 1e7 points the cumtrapz takes close to a second and I see no difference between the first and second call.
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!