Pre-allocating a function since initialization is slow
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Daniel Shub
2012-3-27
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 个评论
Daniel Shub
2012-3-27
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!