Pre-allocating a function since initialization is slow

1 回表示 (過去 30 日間)
Martijn
Martijn 2012 年 3 月 27 日
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.

回答 (1 件)

Daniel Shub
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 件のコメント
Martijn
Martijn 2012 年 3 月 27 日
@Jan Simon: Same thing.
Daniel Shub
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 ExchangeSoftware Development Tools についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by