Why is matlab's fopen so slow?

35 views (last 30 days)
Adam
Adam on 18 Nov 2025 at 9:46
Commented: dpb on 18 Nov 2025 at 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 Comments
Adam
Adam 16 minutes ago

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 about 1 hour ago
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?

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!