Avoid str2double and str2num. Use sscanf instead.
For scalars, you’ll see a modest improvement.
>> str = '0009'; >> tic; for p=1:1000, str2num(str); end; toc Elapsed time is 0.126388 seconds. >> tic; for p=1:1000, sscanf(str, '%d'); end; toc Elapsed time is 0.022299 seconds.
>> str = '3.14159265'; >> tic; for p=1:1000, str2double(str); end; toc Elapsed time is 0.056466 seconds. >> tic; for p=1:1000, sscanf(str, '%f'); end; toc Elapsed time is 0.017805 seconds.
For vectors, you’ll see a more hefty speed up.
>> str = '0009 3.14159265'; >> tic; for p=1:1000, str2double(str); end; toc Elapsed time is 0.480512 seconds. >> tic; for p=1:1000, sscanf(str, '%f'); end; toc Elapsed time is 0.027449 seconds.
Also favor sprintf instead of num2str.
>> tic; for p=1:1000, num2str(p); end; toc
Elapsed time is 0.101599 seconds.
>> tic; for p=1:1000, sprintf('%d', p); end; toc
Elapsed time is 0.018325 seconds.




No user commented in " MATLAB Performance Tricks #1 "
Follow-up comment rss or Leave a TrackbackLeave A Reply