Why is matlab's fopen so slow?

조회 수: 41 (최근 30일)
Adam
Adam 2025년 11월 18일 9:46
댓글: dpb 2025년 11월 18일 17:30
In our codebase, we want to log strings to a file. I use a very simple function for this:
function log(logstring)
fid = fopen("logging.log","A");
fwrite(fid,logstring);
fclose(fid);
end
Problem is that this is very slow (and I'm already using "A", as recommended for speed).
I also have pyton configured on my pc, which opens up the following alternative way to do the same thing:
function log_python(logstring)
filename = "logging.log";
code = ["with open(filename, 'a',encoding='utf-8',newline='') as f:";
" f.write(data)"];
pyrun(code,data=logstring,filename=filename);
end
This method turns out to be about 10x faster than the matlab version. How is this possible?
  댓글 수: 4
Adam
Adam 2025년 11월 18일 17:11

The with statement in python creates a context manager which will close the file correctly after the code inside has run. These two codes just do the same thing.

It is not always possible to keep the file open in between writes, especially when logging in a large codebase which might crash and then leave some file unclosed. So I prefer, for robustness of my codebase do open and close the file each time, something that apparently can be done quickly in python but not in Matlab

dpb
dpb 2025년 11월 18일 17:30
Create an onCleanup function to deal with that if crashes or user Ctrl-C's or the like.
Probably the difference between MATLAB and Python is in system buffering of when data are actually written to the file system. I'm pretty sure MATLAB flushes the buffer every time rather than caching and writing only larger blocks.
Can you verify if the code does crash that all logging data is saved both ways?

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

답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by