Why is matlab's fopen so slow?
Mostra commenti meno recenti
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 Commenti
I will just point out that log is a built-in function (with many different implementations) in MATLAB, best to use a different name for your function.
which log -all
Where in the python version is the file closed? I don't know nuthin' about python so not sure just what the "with open(filename, ..." sequence does, but I wonder if it isn't using the already opened file on subsequent passes as I don't see anything that looks like it would close it unless it's hidden in the write method which one wouldn't think would be so.
My penchant for doing similar is to also open the file at the beginning and then close it when done instead of every time if it's in a tight loop.
Also, is the time required dependent upon the size of the file -- I've not tried testing for it, but the fopen() with the append access requires a move of the file position pointer to the end of the file; wonder if that is taking up more time with longer file.
Adam
il 18 Nov 2025
dpb
il 18 Nov 2025
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?
Risposte (0)
Categorie
Scopri di più su Call Python from MATLAB in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!