how to make fscanf faster
이전 댓글 표시
Hi, all
I have problem with getting data from a sensor using serial communication rs-232. The problem is fscanf takes much time. There is profiler result below.
time calls for i=1:1:1501
2.61 1501 Out(i,1) = eval(fscanf(s));
0.01 1501 end
The sensor provides data(13X1 char) when it is called. I used a for-loop to acquire whole data (1501X13)
1501 calls increase its time. If I reduce the number of calls, the accuracy will be reduced. I want to have high accurate data that means I need to call 1501 times. Is there any way to make fscanf faster? OR any better code to get data faster in serial communication?
Thanks in advance.
채택된 답변
추가 답변 (2개)
Walter Roberson
2013년 1월 29일
2 개 추천
You do not know you are testing the speed of fscanf(): you might be testing the speed of eval(). Are you certain you need eval?
댓글 수: 9
Jong-Hwan Kim
2013년 1월 30일
Walter Roberson
2013년 1월 30일
Do you mean characters such as 'Pi/7' ? Or do you mean characters such as '0.9258e+04' ? If you mean the later, then use fscanf(s, '%f'). If the number of numbers per line is consistent then it is more efficient to repeat the '%f', as in fscanf(s, '%f%f%f%f%f') for 5 space-separated numbers.
EDIT: please, discard this comment and see Jan's comment below!
Following up on Walter comment, you could generate a format string for e.g. 1501 floats with:
fmt = char(repmat('%f', 1, 1501)) ;
values = fscanf(fid, fmt) ;
Jan
2013년 1월 30일
@Cedric: You can omit the "char()", because repmat('%f', 1, 1501) replies a char already. Is this faster than fscanf(fid, '%f', [1, 1501])?
Cedric
2013년 1월 30일
Jan, to be honest, I had forgotten that fscanf can take a size arg!
Jan
2013년 1월 30일
I do not have access to a Matlab computer currently, so I'm not sure which method is faster. A naive C-mex approach to interpret ASCII strings from a file as a decimal number can be much faster than Matlab's FSCANF, see e.g. FEX: str2doubleq. But unfortunately the results are not reliably, e.g. for exceptions like NaN, Inf, malformed numbers, and for numbers which cannot be represented as binary values exactly. Then e.g. the parser of Googles V8 engine is much smarter: http://code.google.com/p/double-conversion/ . But another problem remains, that I do not know an efficient method to access a file from inside a Mex-function, which has been open from Matlab. Therefore I cannot simply plug in the V8 code to create a faster FREAD.
Jong-Hwan Kim
2013년 1월 30일
편집: Jong-Hwan Kim
2013년 1월 30일
Jong-Hwan Kim
2013년 1월 30일
편집: Jong-Hwan Kim
2013년 1월 30일
카테고리
도움말 센터 및 File Exchange에서 Whos에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!