Does "persistent variable" help speed?

22 views (last 30 days)
Nima Alam
Nima Alam on 10 Nov 2015
Commented: Yair Altman on 11 Nov 2015
Hi, I have a heavy Simulink model with many Matlab function blocks. I deliver C-Code generated from my model to run on a hardware platform. I am wondering if using persistent variables inside Matlab function blocks improves the execution speed or not? Comments appreciated. Thanks!

Answers (1)

Yair Altman
Yair Altman on 11 Nov 2015
Persistent variables can indeed improve execution speed if you use them in a wise manner that utilizes their benefits, i.e. to cache data across separate function invocations, thereby saving the need to reload or recompute the data in each invocation. Of course, you need to ensure that caching the data is ok for your specific algorithm. After all, a fast but incorrect result will always be inferior to a slow but correct one. If you do not use caching, then persistent variables will have no useful performance impact.
In addition to caching, any other improvement to the performance of your Matlab code will naturally improve your model's overall performance.
  2 Comments
Nima Alam
Nima Alam on 11 Nov 2015
Thanks a lot Yair! for your explanation. I think I should ask my question in a better way. Actually, I knew that persistent variables help speed through eliminating the need for reloading/re-computation of variables across separate function invocations.
My question is about those temporary variables which need to be computed/defined at each functions call anyway, without any need to be reloaded in the next epoch. I was wondering that memory allocation method for persistent variables can improve the speed, if I define the normal/temporary variables as persistent?
Yair Altman
Yair Altman on 11 Nov 2015
I do not think so. In fact, using temp (not persistent) variables could possibly be optimized internally by Matlab to use registers/stack, which would be faster than using main memory (heap) as is the case for persistent/global vars. Even if this is not optimized, the potential speed savings are probably negligible.

Sign in to comment.

Categories

Find more on Event Functions in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!