Why does str2num take much longer to convert 1001 long char array apposed to a 1000 long char array (MatLab R2010b 64bit, on Win 64bit)

조회 수: 2(최근 30일)
%make 1001-by-3 char array of numbers, can replace 3 with any size
t = '0123456789';
t = t(ceil(rand(3,1001)*10))';
%big difference in time needed to convert 1000 vs 1001 numbers
tic,n1000 = str2num(t(1:1000,:));toc
tic,n1001 = str2num(t(1:1001,:));toc
% Elapsed time is 0.000285 seconds.
% Elapsed time is 0.011493 seconds.
%results are identical
all(n1000 == n1001(1:1000))
%ans =
% 1
  댓글 수: 1
Serge 2023년 3월 11일
It's now 2023 and the performance step change of str2num is still there but now in a different place...
str2num is still 4x faster then str2double in this situation.
(R2022b, Win10)
str1 = num2str(rand(15384,1)); %list of numbers as char, 15384-by-10
str2 = num2str(rand(15385,1)); %list of numbers as char, 15385-by-10
timeit(@()str2num(str1)) %0.002 sec FAST
timeit(@()str2num(str2)) %0.046 sec 20x slower
timeit(@()str2double(str1)) %0.009 sec 4x slower
timeit(@()str2double(str2)) %0.009 sec 4x slower

댓글을 달려면 로그인하십시오.


Walter Roberson
Walter Roberson 2016년 6월 1일
You should use timeit() from the File Exchange to get more accurate timing. (timeit was eventually made part of MATLAB.)
I do see more of a difference than I would expect in R2016a on OS-X.
I recommend you switch to str2double()
  댓글 수: 2
Walter Roberson
Walter Roberson 2016년 6월 2일
f = @() str2double(t1000); t7 = timeit(f)
f = @() str2double(t1001); t8 = timeit(f)
On my system it is not as fast as t1 or t2 but it is faster than any of the others.

댓글을 달려면 로그인하십시오.

Steven Lord
Steven Lord 2023년 3월 11일
What's your ultimate goal here, of which I suspect this conversion is one step in a larger process?
If you want to generate 1000 (or 1001) 3-digit numbers I wouldn't work with char arrays at all. Just create the data as numbers in the first place.
x = randi([100 999], 1001, 1);
Elapsed time is 0.003874 seconds.
If you're trying to convert data that you read in from a file as text into numbers, why not read that data in as numbers in the first place? If you're using functions like readtable or readmatrix set the import options created by detectImportOptions to read the data in using a numeric data type.
If you're trying to do something else and you can explain that task in more detail we may be able to offer more specific suggestions.

Community Treasure Hunt

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

Start Hunting!

Translated by